I have two tables in my database - MPRS and ALL_SSC. I want to update the ALL_SSC table with data from MPRS and in Access (where I test my SQL) it works.
However, when I run it in my VB 2010 program on the SQL Server database, it says table MPRS already exists.
I know it does! I'm not trying to create it. I'm updating FROM it... any ideas where this SQL is wrong?
SQL = "UPDATE ALL_SSC LEFT JOIN MPRS ON MPRS.MPAN = ALL_SSC.MPAN1 SET ALL_SSC.PC1 = Format([mprs].[pc],'00'), ALL_SSC.MSPCDC1 = Mid([mprs].[PC_EFD],7,4) & Mid([mprs].[PC_EFD],4,2) & Mid([mprs].[PC_EFD],1,2), ALL_SSC.MTSC1 = [mprs].[MTC], ALL_SSC.MSMCDC1 = Mid([mprs].[MTC_EFD],7,4) & Mid([mprs].[MTC_EFD],4,2) & Mid([mprs].[MTC_EFD],1,2), ALL_SSC.LLF1 = [mprs].[LLF], ALL_SSC.SUPPLIER1 = [mprs].[SUPPLIER], ALL_SSC.REGI1 = Mid([mprs].[SSD],7,4) & Mid([mprs].[SSD],4,2) & Mid([mprs].[SSD],1,2), ALL_SSC.ENG_STATUS1 = 0 WHERE (((ALL_SSC.MPAN1) Is Not Null) AND ([mprs].[ENERG_STATUS]='E'));"
cmd = New SqlCommand(sSQL, cNN)
Try
Try
If cNN.State <> ConnectionState.Open Then
cNN.Open()
End If
Catch exCnn As Exception
MsgBox(exCnn.Message)
End Try
cmd.ExecuteNonQuery()
Catch ex As Exception
MsgBox("Cannot continue. " & ex.Message)
Exit Sub
End Try
You have accidentally used variable "sSQL" when you meant to use "SQL".
Yet another example of why meaningful variable names are important.
The correct syntax for a JOIN with UPDATE in SQL Server is:
UPDATE a
SET PC1 = . . .
FROM ALL_SSC a LEFT JOIN
MPRS m
ON m.MPAN = a.MPAN1
WHERE . . .;
That is, you need a FROM clause and it comes after the SET.
Thanks Gordon for your help. One or two other changes needed to move from Access SQL to SQL Server, but this is the SQL i ended up with working in SQL Server.
UPDATE a
SET
a.PC1 = '0' + m.[pc],
a.MSPCDC1 = substring(m.[PC_EFD],7,4) + substring(m.[PC_EFD],4,2) + substring(m.[PC_EFD],1,2),
a.MTSC1 = m.[MTC],
a.MSMCDC1 = substring(m.[MTC_EFD],7,4) +substring(m.[MTC_EFD],4,2) + substring(m.[MTC_EFD],1,2),
a.LLF1 = m.[LLF],
a.SUPPLIER1 = m.[SUPPLIER],
a.REGI1 = substring(m.[SSD],7,4) + substring(m.[SSD],4,2) + substring(m.[SSD],1,2),
a.ENG_STATUS1 = 0
FROM [myDataBase].[dbo].ALL_SSC a LEFT JOIN
[myDataBase].[dbo].MPRS m
ON m.MPAN = a.MPAN1
WHERE (((a.MPAN1) Is Not Null) AND (m.[ENERG_STATUS]='E'));
However, When I execute the exact same code on the database via VB 2010, I get the same failure message. This is the vb code
For iMPAN As Integer = 1 To 3
'mpan - energised
SQL = "UPDATE a SET a.PC" + iMPAN.ToString + " = '0' + m.[pc], a.MSPCDC" + iMPAN.ToString + " = substring(m.[PC_EFD],7,4) + substring(m.[PC_EFD],4,2) + substring(m.[PC_EFD],1,2), a.MTSC" + iMPAN.ToString + " = m.[MTC], a.MSMCDC" + iMPAN.ToString + " = substring(m.[MTC_EFD],7,4) +substring(m.[MTC_EFD],4,2) + substring(m.[MTC_EFD],1,2), a.LLF" + iMPAN.ToString + " = m.[LLF], a.SUPPLIER" + iMPAN.ToString + " = m.[SUPPLIER], a.REGI" + iMPAN.ToString + " = substring(m.[SSD],7,4) + substring(m.[SSD],4,2) + substring(m.[SSD],1,2), a.ENG_STATUS" + iMPAN.ToString + " = 0 FROM ALL_SSC a LEFT JOIN MPRS m ON m.MPAN = a.MPAN1 WHERE (((a.MPAN" + iMPAN.ToString + ") Is Not Null) AND (m.[ENERG_STATUS]='E'));"
Debug.Print(SQL)
cmd = New SqlCommand(sSQL, cNN)
Try
Try
If cNN.State <> ConnectionState.Open Then
cNN.Open()
End If
Catch exCnn As Exception
MsgBox(exCnn.Message)
End Try
cmd.ExecuteNonQuery()
Catch ex As Exception
Debug.Print(ex.Message)
MsgBox("Cannot continue. " & ex.Message)
Exit Sub
End Try
Next
Related
I have a VBA script that makes a call to SSMS to run a query and paste the results into Excel. I have this same code used for 2 other queries prior to this one and they both work, but this one gives the error for some reason.
I originally thought it was due to the Temp tables, so I added "set nocount on" to the beginning, but it didn't help. Any tips or recommendations are appreciated!
Error Message:
Run-time error '3704':
Operation is not allowed when the object is closed.
Sub Test()
'Setup variables
Dim cnn As New ADODB.Connection
Dim rst As New ADODB.Recordset
Dim ConnectionString As String
Dim StrQuery As String
Dim SOURCE As String
Dim DATABASE As String
Dim QUERY As String
Dim intColIndex As Integer
'Assign variables
SOURCE = [Data Source]
DATABASE = [Database]
QUERY = "set nocount on"
QUERY = QUERY + " declare #Variable1 int"
QUERY = QUERY + " declare #Variable2 int"
QUERY = QUERY + " declare #Variable3 datetime"
QUERY = QUERY + " declare #Variable4 datetime"
QUERY = QUERY + " select #Variable1 = [xxxx]"
QUERY = QUERY + " select #Variable2=(select Field1 from Table1 where Field2 = #Variable1)"
QUERY = QUERY + " select #Variable3=min(Variable3) from Table2 where Field3=#Variable2"
QUERY = QUERY + " select #Variable4=max(Field4) from Table2 where Field3=#Variable2"
QUERY = QUERY + " select distinct b.Field5, b.Field10 into #Temp1"
QUERY = QUERY + " from Table3 p(nolock)"
QUERY = QUERY + " inner join Table4 b(nolock) on b.Field5 = p.fkField5"
QUERY = QUERY + " inner join Table5 cp (nolock) on cp.Field6 = p.Field11"
QUERY = QUERY + " where Field3=#Variable2 "
QUERY = QUERY + " select Field3,Field9,Variable3,Field4 into #Temp2 from Table2 cf (nolock)"
QUERY = QUERY + " inner join Table6 ac (nolock) on ac.Field7=cf.Field3"
QUERY = QUERY + " where Variable3 >= #Variable3 - 365 and Field4 < #Variable4 + 1"
QUERY = QUERY + " and ac.Field8 <>4"
QUERY = QUERY + " select distinct cp.Field3,Field9,convert(varchar(10),Variable3,101) Variable3,convert(varchar(10),Field4,101) Field4"
QUERY = QUERY + " from Table5 cp (nolock)"
QUERY = QUERY + " inner join Table3 p (nolock) on p.Field11=cp.Field6"
QUERY = QUERY + " inner join Table4 b (nolock) on b.Field5 = p.fkField5"
QUERY = QUERY + " inner join #Temp1 bb on bb.Field5=b.Field5"
QUERY = QUERY + " inner join #Temp2 oth on oth.Field3=cp.Field3"
QUERY = QUERY + " drop table #Temp1"
QUERY = QUERY + " drop table #Temp2"
'Run the query and paste results into Cell X11 on the first tab of the workbook
ConnectionString = "Provider=SQLOLEDB;Data Source=" & SOURCE & "; Initial Catalog=" & DATABASE & "; Integrated Security=SSPI;"
cnn.Open ConnectionString
cnn.CommandTimeout = 900
StrQuery = QUERY
rst.Open StrQuery, cnn
Sheets(1).Range("X11").CopyFromRecordset rst
'Add the column headers
For intColIndex = 0 To rst.Fields.Count - 1
Range("X10").Offset(0, intColIndex).Value = rst.Fields(intColIndex).Name
Next
End Sub
In c# Windows Forms:
I'm having trouble adding a sql query result as text to a ToolStripMenuItem.Text.
The ToolStripMenuItem title should be, the company + how many orders there are in the sql table for this company which should update every x secounds.
Every 5 seconds it adds the query result to the text. My problem is that is "adds" it.
After the first 5 seconds it looks OK "rexton 1" but 5 seconds after it shows "rexton 1 1" and so on...
Here is my code:
//Rexton ordre klar til bestilling
SqlConnection con = new SqlConnection(#"Data Source=" + globalvariables.hosttxt + "," + globalvariables.porttxt + "\\SQLEXPRESS;Database=ha;Persist Security Info=false; UID='" + globalvariables.user + "' ; PWD='" + globalvariables.psw + "'");
SqlCommand command = con.CreateCommand();
command.CommandText = "SELECT COUNT(*) from bestillinger WHERE firma = #rexton and udlevering BETWEEN #date and #dateadd";
command.Parameters.AddWithValue("#bernafon", "Bernafon");
command.Parameters.AddWithValue("#gn_resound", "GN Resound");
command.Parameters.AddWithValue("#oticon", "Oticon");
command.Parameters.AddWithValue("#phonak", "Phonak");
command.Parameters.AddWithValue("#rexton", "Rexton");
command.Parameters.AddWithValue("#siemens", "Siemens");
command.Parameters.AddWithValue("#widex", "Widex");
con.Open();
command.ExecuteNonQuery();
string result = command.ExecuteScalar().ToString();
con.Close();
if (result != "0")
{
rextonToolStripMenuItem.Text = rextonToolStripMenuItem.Text + " " + result;
rextonToolStripMenuItem.ForeColor = System.Drawing.ColorTranslator.FromHtml("#FF1919");
}
it is because you are setting rextonToolStripMenuItem.Text to rextonToolStripMenuItem.Text + " " + result which is appending to previous text
either set text to blank and set it again or just say
rextonToolStripMenuItem.Text = "rexton " + result
Is there any way to get the table adapter to insert the values already in the dataset I pass it when inserting new rows?
I am synchronising two databases and this would be useful.
Here is currently how I am trying to do it but it auto increments and creates new identity values.
Dim dAdapterConstraints As New SqlClient.SqlDataAdapter("SELECT * FROM " + Tablename, _oConn)
Dim builder As SqlCommandBuilder = New SqlCommandBuilder(dAdapterConstraints)
builder.QuotePrefix = "["
builder.QuoteSuffix = "]"
dAdapterConstraints.InsertCommand = builder.GetInsertCommand
Dim insertcommandstr As String = dAdapterConstraints.InsertCommand.CommandText.Substring(0, dAdapterConstraints.InsertCommand.CommandText.IndexOf("(") + 1) + " [" + Primarykey + "], " + dAdapterConstraints.InsertCommand.CommandText.Substring(dAdapterConstraints.InsertCommand.CommandText.IndexOf("(") + 1, dAdapterConstraints.InsertCommand.CommandText.Length - (dAdapterConstraints.InsertCommand.CommandText.IndexOf("(") + 1))
insertcommandstr = insertcommandstr.Replace("#p1", "#po1, #p1")
dAdapterConstraints.InsertCommand.Parameters.Add("#po1", getdbtype(dataset.Tables(0).Columns(Primarykey).DataType), dataset.Tables(0).Columns(Primarykey).MaxLength, Primarykey)
insertcommandstr = "SET IDENTITY_INSERT [" + Tablename + "] ON " + insertcommandstr + " SET IDENTITY_INSERT [" + Tablename + "] OFF"
dAdapterConstraints.InsertCommand.CommandText = insertcommandstr
dataset.EnforceConstraints = False
' opens connection
'fills dataset with results
Try
For Each row As DataRow In dataset.Tables(0).Rows
row.SetAdded()
Next
dAdapterConstraints.Update(dataset)
Catch ex As Exception
_oConn.Close()
MsgBox("Could not execute query on server database," + ex.ToString + ";Updating and inserting")
Return False
End Try
Here is my Code:
Dim CompanyName, _
CompanyDomain, _
CompanyEmail, _
CompanySupportPhone
Call GetEmailList
Sub GetEmailList
dim sql
dim companydata
sql = ""
sql = sql & " DECLARE #CompanyName VARCHAR(100);"
sql = sql & " DECLARE #CompanyDomain VARCHAR(100);"
sql = sql & " DECLARE #CompanyActivityEmail VARCHAR(100);"
sql = sql & " DECLARE #CompanySupportPhone VARCHAR(100);"
sql = sql & " SELECT"
sql = sql & " #CompanyName = CASE WHEN Setting = 'CompanyName'"
sql = sql & " THEN StringValue ELSE #CompanyName END,"
sql = sql & " #CompanyDomain = CASE WHEN Setting = 'CompanyDomain'"
sql = sql & " THEN StringValue ELSE #CompanyDomain END,"
sql = sql & " #CompanyActivityEmail = CASE WHEN Setting = 'CompanyActivityEmail'"
sql = sql & " THEN StringValue ELSE #CompanyActivityEmail END,"
sql = sql & " #CompanySupportPhone = CASE WHEN Setting = 'CompanySupportPhone'"
sql = sql & " THEN StringValue ELSE #CompanySupportPhone END"
sql = sql & " FROM ClientSettings"
sql = sql & " WHERE Setting in ('CompanyDomain','CompanyActivityEmail','CompanySupportPhone','CompanyName')"
sql = sql & " SELECT ISNULL(#CompanyName, '') AS CompanyName, ISNULL(#CompanyDomain, '') AS CompanyDomain, ISNULL(#CompanyActivityEmail, '') AS CompanyEmail, ISNULL(#CompanySupportPhone, '') AS CompanySupportPhone"
set companydata = getRecordset(sql)
CompanyName = companydata("CompanyName") ' LINE 80
CompanyDomain = companydata("CompanyDomain")
CompanyEmail = companydata("CompanyEmail")
CompanySupportPhone = companydata("CompanySupportPhone")
companydata.Close
Set companydata = Nothing
End Sub
This throws an error:
Line 80
Item cannot be found in the collection corresponding to the requested
name or ordinal.
I marked line 80 above. I run this exact same SQL in SQL Server Manager and it returns results:
CompanyName CompanyDomain CompanyEmail CompanySupportPhone
MyCompanyName http://localhost MyCompanyName#email.com 801-555-1212
Any idea what I am doing wrong here?
GetRecordSet correctly loads and processes the database call, this function works in 1,000 other places. I'm sure the problem isn't there.
Add
sql = sql & " SET NOCOUNT ON;"
as the first SQL statement.
SET NOCOUNT ON usage
"There is no row at position 0."
Hi I keep on getting this error message.
If mytable.Rows.Count >= 0 then
dim myid = dt.Rows(0).Item(6).ToString
End if
Please help me in this matter and I would never ever like to see this message again.Thanking you all.
qry_Sql = qry_Sql + " select SRNO,EMPNO,ATTN_YR,ATTN_MONTH,"
qry_Sql = qry_Sql + " GRP,TOT_HRS,MY_ID "
qry_Sql = qry_Sql + " from ATTD_HRS "
qry_Sql = qry_Sql + " ORDER BY EMP_NO "
If mytable.Rows.Count <= 0 Then
mygrp = dt.Rows(0).Item(5).ToString ---------------------
myid = dt.Rows(0).Item(6).ToString
End If
You should check to see if your table contains any rows...
If mytable.rows.Count > 0 then
If mytable.rows(0).items(2) >= 0 then
dim myid = dt.Rows(0).Item(6).ToString
End if
End if
Probably because mytable has no row at position 0, (rows(0) part).
You should check if there are rows/items before using them.