SQL delete query on non key column - sql-server

I'm new to the SQL query language and I'm trying to figure out how to delete a row (in a SQL DB table) with a non key ID column value using vb.net. For example in the table TEST below:
ID Name
1 x
2 y
3 z
I have a windows form that the user selects the Name value, however when I run my code it says
Cannot convert varchar "y" to int.
Here is my code attempt:
Dim sConnectionString As String
sConnectionString = "Data Source=" + serverName + ";Initial Catalog=" + dbName + ";Integrated Security=SSPI;"
Dim objConn As New SqlConnection(sConnectionString)
objConn.Open()
Dim cmd As New SqlCommand
cmd.Connection = objConn
cmd.CommandText = "DELETE FROM TEST WHERE Name = y"
cmd.ExecuteNonQuery()
Thank you!

If your Name column is of type varchar you need to enclose the value in single quotes
cmd.CommandText = "DELETE FROM TEST WHERE Name = 'y'"
A complete answer to your question will be:
Dim sConnectionString As String
sConnectionString = "Data Source=" + serverName + _
";Initial Catalog=" + dbName + _
";Integrated Security=SSPI;"
Dim objConn As SqlConnection
Using(objConn = new SqlConnection(sConnectionString)
objConn.Open()
Dim cmd As New SqlCommand
cmd.Connection = objConn
cmd.CommandText = "DELETE FROM TEST WHERE Name = #name"
cmd.Parameters.AddWithValue("#name", txtName.Text)
cmd.ExecuteNonQuery()
End Using
I'm supposing that your user insert the name to delete in a textbox and you pass this value to a parametrized query. The use of parametrized query will save you from the hassle to handle quoting problems and from Sql Injection Attacks

If you do this you will be deleting all rows WHERE Name = y and you probably don't want to do that.
You should use the name in the UI but pass the ID to SQL.
If you really do want to delete ALL rows with that name then put quotes around the y, as without them it's looking for a column named y:
DELETE FROM TEST WHERE Name = 'y'

cmd.CommandText = "DELETE FROM TEST WHERE Name = y";
instead you can use this one
cmd.CommandText = "DELETE FROM TEST WHERE ID = " + idValue;
here the 'idValue' is the ID that u take from the user
OR OTHER WISE
cmd.CommandText = "DELETE FROM TEST WHERE Name = 'y'";

Related

Working with GUIDs in Acces and SQL Server database - insert GUID value into UNIQUEIDENTIFIER column

I have a SQL Server database linked to a MS Access frontend.
I'm trying to store a GUID value in a UNIQUEIDENTIFIER field named FileSorceID. The GUID which I want to store there comes from the GUID of my current recordset (Me!GUID) which is also an UNIQUEIDENTIFIER and is created directly within the SQL server. This GUID shall be stored in my table.
But I always get an error -2147217887 (80040e21) when trying to do this.
So I already have a GUID which I just want to store in a different table in an UNIQUEIDENTIFIER field. All solutions I've found were discussing about creating a new GUID within SQL Server but I already have one that I just need to store.
strCnxn = "Provider=sqloledb;" & _
"Data Source=MYSERVER;" & _
"Initial Catalog=MYDATABASE;" & _
"Integrated Security=SSPI;" 'Windows-Authentication
Set cn = CreateObject("ADODB.Connection")
cn.Open strCnxn
'Recordset
sql = "AttachmentsFileStream" 'Table to add file
Set rs = CreateObject("ADODB.Recordset")
rs.Open sql, strCnxn, 1, 3 '1 - adOpenKeyset, 3 - adLockOptimistic"
Dim GUID As Variant
GUID = Me!GUID.Value
GUID = StringFromGUID(Me.GUID.Value)
GUID = Replace(GUID, "{guid {", "")
GUID = Replace(GUID, "}}", "")
'GUID will now hold the string "39A0483A-AE4C-44B5-94C3-00267185B81E"
'Insert into database
rs.AddNew 'FileId (also a GUID) will be automatically handled by SQL
rs!FileName = FileName
rs!FileSourceID = GUID
rs!HideFile = False
'Clean up
rs.Update
rs = Nothing
I've also tried to leave out the string conversion with same result.
It always stops at this line of code:
rs!FileSourceID = GUID
I found the solution, you need to include {and }around the GUID when you want to insert it via MS Access.
Working code:
strCnxn = "Provider=sqloledb;" & _
"Data Source=MYSERVER;" & _
"Initial Catalog=MYDATABASE;" & _
"Integrated Security=SSPI;" 'Windows-Authentication
Set cn = CreateObject("ADODB.Connection")
cn.Open strCnxn
'Recordset
sql = "AttachmentsFileStream" 'Table to add file
Set rs = CreateObject("ADODB.Recordset")
rs.Open sql, strCnxn, 1, 3 '1 - adOpenKeyset, 3 - adLockOptimistic"
Dim GUID As Variant
GUID = Me.GUID.Value 'needs to be a field in the form
GUID = StringFromGUID(GUID)
GUID = Replace(GUID, "{guid {", "{")
GUID = Replace(GUID, "}}", "}")
'GUID will now hold the string like "{39A0483A-AE4C-44B5-94C3-00267185B81E}"
'Insert into database
rs.AddNew 'FileId (also a GUID) will be automatically handled by SQL
rs!FileName = FileName
rs!FileSourceID = GUID
rs!HideFile = False
'Update recordset in SQL
rs.Update

Search Another Type Text SQL Server VB.Net

I have a problem with search: how do I search our language text from SQL query and which type data I select
Dim cmd As New SqlCommand
cmd.Connection = cn
cmd.CommandText = "SELECT * FROM Table_12 WHERE m='" & "دولت خان" & "'"
Dim adapter As New SqlDataAdapter(cmd)
Dim table As New DataTable()
adapter.Fill(table)
If table.Rows.Count() > 0 Then
TextBox2.Text = table.Rows(0)(1).ToString()
MessageBox.Show("Record found!")
Else
MessageBox.Show("Record not found!")
Keep your database objects local so you can control that they are closed and disposed. A single Using...End Using block handles this for you.
You can pass your connection string directly to the constructor of the connection and pass the command text and connection directly to the constructor of the command.
Always use parameters to avoid Sql Injection. The value concatenated to an sql command string is potentially executable. Parameter values are not.
Private Sub OpCode()
Dim dt As New DataTable
Using cn As New SqlConnection("Your connection string"),
cmd As New SqlCommand("SELECT * FROM Table_12 WHERE m= #m;", cn)
cmd.Parameters.Add("#m", SqlDbType.NVarChar, 50).Value = "دولت خان"
cn.Open()
dt.Load(cmd.ExecuteReader)
End Using
If dt.Rows.Count() > 0 Then
TextBox2.Text = dt.Rows(0)(1).ToString()
MessageBox.Show("Record found!")
Else
MessageBox.Show("Record not found!")
End If
End Sub
Search with like clause for unicode in column m and show column o:
cmd.CommandText = "SELECT o FROM Table_12 WHERE m like N'%" & "دولت خان" & "%'"

Running SQL Server query in VB.NET

How would I create a query that returns a column in the database? The SQL select statement is easy. I'm having issues with the VB side.
SELECT UserNO
FROM UserTable
WHERE UserID = user;
I need to then get that UserNO and pass it to another T-SQL stored procedure. How would I go about running a SELECT query and getting the results back in Visual Basic?
Attached is some of my code. The code below adds the user to the DB however the UserNo (INTEGER) is automatically generated by SQL Server as the INSERT statement is run in the insert stored procedure, so I need to pull the UserNO after the user is created.
Public conwd As SqlConnection = New SqlConnection("Server=*****;Database=*****;User Id=****;Password=****")
Public conwp As SqlConnection = New SqlConnection("Server=*****;Database=*****;User Id=****;Password=****")
Dim cmdP As SqlCommand = New SqlCommand("EXECUTE [dbo].[AddNewUserWestonTemp] '" + user + "'", conwp)
Dim cmdD As SqlCommand = New SqlCommand("EXECUTE [dbo].[AddNewUserWestonTemp] '" + user + "'", conwd)
conmp.Open()
conmd.Open()
cmdP.ExecuteNonQuery()
cmdD.ExecuteNonQuery()
The Using..End Using blocks close and dispose of your data objects that might contain unmanaged code. The Parameters help prevent SQL injection.
Private Sub OPCode2()
Dim newID As Integer
Dim sql = "Insert Into UserTable (User) Values (#User); Select SCOPE_IDENTITY();"
Using cn As New SqlConnection("Your Connection String")
Using cmd As New SqlCommand(sql, cn)
cmd.Parameters.Add("#User", SqlDbType.NVarChar).Value = "Brian Weaver"
cn.Open()
newID = CInt(cmd.ExecuteScalar)
End Using
End Using
'Use the newID in your next command
UserStoredProcedure(newID)
End Sub
Private Sub UseStoredProcedure(id As Integer)
Dim sql = "InsertSomeUserInfo" 'the name of your stored procedure
Using cn As New SqlConnection("Your Connection String")
Using cmd As New SqlCommand(sql, cn)
cmd.CommandType = CommandType.StoredProcedure
'whatever parameter names and types your stored procedure uses
cmd.Parameters.Add("#UserID", SqlDbType.Int).Value = id
cmd.Parameters.Add("#Salary", SqlDbType.Decimal).Value = 50000
cn.Open()
cmd.ExecuteNonQuery()
End Using
End Using
End Sub
Dim cmdP As SqlCommand = New SqlCommand("EXECUTE [dbo].[AddNewUserWestonTemp] '" + user + "'" + "; SELECT CAST(scope_identity() AS int", conwp)
Dim userNo as Integer = cmdP.ExecuteScalar()
ExecuteScalar retrieves the first line of the result

Importing MS Access to MS SQL Server

Currently trying to update an SQL Server database from an Access db, it works importing new records but fails on when I reimport the file and there is a duplicate - in looking for it to insert the row if it's not there (working), but skip if it already exists. The first column has the primary key set.
Dim table As DataTable = New DataTable
Dim accConnection As New OleDb.OleDbConnection(
"Provider=Microsoft.JET.OLEDB.4.0; Data Source='C:\Tester.mdb';User Id=admin; Password=;")
Dim sqlConnection As New SqlClient.SqlConnection(
"Data Source=10.75.24.94;Initial Catalog=CTData;User ID=sql;Password=")
Try
'Import the Access data
accConnection.Open()
Dim accDataAdapter = New OleDb.OleDbDataAdapter(
"SELECT * FROM Import_test", accConnection)
accDataAdapter.Fill(table)
accConnection.Close()
'Export to MS SQL
For Each row As DataRow In table.Rows
row.SetAdded()
Next
sqlConnection.Open()
Dim sqlDataAdapter As New SqlClient.SqlDataAdapter(
"SELECT * FROM Import_test", sqlConnection)
Dim sqlCommandBuilder As New SqlClient.SqlCommandBuilder(sqlDataAdapter)
sqlDataAdapter.InsertCommand = sqlCommandBuilder.GetInsertCommand()
sqlDataAdapter.UpdateCommand = sqlCommandBuilder.GetUpdateCommand()
sqlDataAdapter.DeleteCommand = sqlCommandBuilder.GetDeleteCommand()
sqlDataAdapter.Update(table)
sqlConnection.Close()
Catch ex As Exception
If accConnection.State = ConnectionState.Open Then
accConnection.Close()
End If
If sqlConnection.State = ConnectionState.Open Then
sqlConnection.Close()
End If
MessageBox.Show("Import failed with error: " &
Environment.NewLine & Environment.NewLine &
ex.ToString)
End Try
The error I'm presented with is:
Violation of Primary key. Cannot insert duplicate key in object.
I think you can remove VB from the equation (I like to make things as simple as possible, without over-simplifying it). You have several options available.
INSERT INTO Table
SELECT * FROM #Table xx
WHERE NOT EXISTS (SELECT 1 FROM Table rs WHERE rs.id = xx.id)
Or . . .
DELETE FROM Table
WHERE (ID NOT IN (SELECT MAX(ID) AS Expr1
FROM Table
AS Table_1 GROUP BY NAME,ADDRESS,CITY,STATE,ZIP,PHONE,ETC.))
There are a lot of other ways to handle this as well. Is you need to incorporate VB, you can do something like this.
Dim cmd As New OleDbCommand
Dim con As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\your_path\DB.accdb")
Dim queryResult As Integer
Dim sqlQRY As String = "SELECT COUNT(*) AS FROM ESRRegister WHERE ID = '" & IDtxt.Text & "'"
con.Open()
cmd.Connection = con
cmd.CommandType = CommandType.Text
If queryResult > 0 Then
cmd.CommandText = "insert into ESRRegister (Dt,ID)VALUES ('" & Dttxt.Text & "' , '" & IDtxt.Text & "')"
queryResult = cmd.ExecuteScalar()
MsgBox("Added Successfuly")
Else
MessageBox.Show("Already Exists!", "ALI ENTERPRISES", MessageBoxButtons.OK, MessageBoxIcon.Information)
End If

Querying a SQL Server in Excel with a parameterized query using VBA

I'm trying to query a table in Microsoft Excel using VBA. I've written up some code to try and accomplish this task, but I keep getting a run-time error '1004' saying it's a General ODBC error. I'm not sure what I need to do to get this code to run properly so I can query this table.
I'm using SQL Server Express, the server I'm connecting to: .\SQLEXPRESS
Database:
Databaselink
Querying the products table
VBA Code:
Sub ParameterQueryExample()
'---creates a ListObject-QueryTable on Sheet1 that uses the value in
' Cell Z1 as the ProductID Parameter for an SQL Query
' Once created, the query will refresh upon changes to Z1.
Dim sSQL As String
Dim qt As QueryTable
Dim rDest As Range
'--build connection string-must use ODBC to allow parameters
Const sConnect = "ODBC;" & _
"Driver={SQL Server Native Client 10.0};" & _
"Server=.\SQLEXPRESS;" & _
"Database=TSQL2012;" & _
"Trusted_Connection=yes"
'--build SQL statement
sSQL = "SELECT *" & _
" FROM TSQL2012.Production.Products Products" & _
" WHERE Products.productid = ?;"
'--create ListObject and get QueryTable
Set rDest = Sheets("Sheet1").Range("A1")
rDest.CurrentRegion.Clear 'optional- delete existing table
Set qt = rDest.Parent.ListObjects.Add(SourceType:=xlSrcExternal, _
Source:=Array(sConnect), Destination:=rDest).QueryTable
'--add Parameter to QueryTable-use Cell Z1 as parameter
With qt.Parameters.Add("ProductID", xlParamTypeVarChar)
.SetParam xlRange, Sheets("Sheet1").Range("Z1")
.RefreshOnChange = True
End With
'--populate QueryTable
With qt
.CommandText = sSQL
.CommandType = xlCmdSql
.AdjustColumnWidth = True 'add any other table properties here
.BackgroundQuery = False
.Refresh
End With
Set qt = Nothing
Set rDest = Nothing
End Sub
I found this Stack Overflow question with a Google search. It does not look like anyone has tried answering it, so here's what I ended up doing. Instead of using "QueryTable", use an ADO command object as done in this MSDN article.
MSDN Example:
Dim Conn1 As ADODB.Connection
Dim Cmd1 As ADODB.Command
Dim Param1 As ADODB.Parameter
Dim Rs1 As ADODB.Recordset
Dim i As Integer
' Trap any error/exception.
On Error Resume Next
' Create and Open Connection Object.
Set Conn1 = New ADODB.Connection
Conn1.ConnectionString = "DSN=Biblio;UID=admin;PWD=;"
Conn1.Open
' Create Command Object.
Set Cmd1 = New ADODB.Command
Cmd1.ActiveConnection = Conn1
Cmd1.CommandText = "SELECT * FROM Authors WHERE AU_ID < ?"
' Create Parameter Object.
Set Param1 = Cmd1.CreateParameter(, adInteger, adParamInput, 5)
Param1.Value = 5
Cmd1.Parameters.Append Param1
Set Param1 = Nothing
' Open Recordset Object.
Set Rs1 = Cmd1.Execute()

Resources