Using SQL script through vb.net code - sql-server

I am new to SQL Server. I often find scripts over internet to perform different functions with SQL Server but I donot know how to use them in vb.net.
For example I want to run the following code through my vb.net application, but donot know how to do so. Please advise
ALTER LOGIN sa ENABLE ;
GO
ALTER LOGIN sa WITH PASSWORD = '' ;
GO
Thanks

The following code might help. Its from http://www.daniweb.com/software-development/vbnet/code/216920
'Declare outside of class
Imports System.Data.SqlClient
'Declare inside of class >
Dim SQLStr As String
Private ConnString As String
'Connstring = Server Name, Database Name, Windows Authentication
connstring = "Data Source=myserver;Initial Catalog=databasename;Integrated Security=True"
'SQL Staments
'SQL query = myQuery = "SQL Statment"
SQLStr = "SELECT * FROM tblQuestion"
SQLStr = "INSERT into tblQuestion(Name, Question) VALUES('Fred', 'How to use SQL?')"
SQLStr = "UPDATE tblQuestion SET Answer = 'Like this' Where Question = 'How to use SQL?'"
SQLStr = "DELETE FROM tblQuestion WHERE Question='How to use SQL?'"
'Write to SQL
Dim SQLConn As New SqlConnection() 'The SQL Connection
Dim SQLCmd As New SqlCommand() 'The SQL Command
SQLConn.ConnectionString = ConnString 'Set the Connection String
SQLConn.Open 'Open the connection
SQLCmd.Connection = SQLConn 'Sets the Connection to use with the SQL Command
SQLCmd.CommandText = SQLStr 'Sets the SQL String
SQLCmd.ExecuteNonQuery() 'Executes SQL Commands Non-Querys only
SQLConn.Close() 'Close the connection
'Read from SQL
Dim SQLConn As New SqlConnection() 'The SQL Connection
Dim SQLCmd As New SqlCommand() 'The SQL Command
Dim SQLdr As SqlDataReader 'The Local Data Store
SQLConn.ConnectionString = ConnString 'Set the Connection String
SQLConn.Open 'Open the connection
SQLCmd.Connection = SQLConn 'Sets the Connection to use with the SQL Command
SQLCmd.CommandText = SQLStr 'Sets the SQL String
SQLdr = SQLCmd.ExecuteReader 'Gets Data
While dr.Read() 'While Data is Present
MsgBox(dr("Column Name")) 'Show data in a Message Box
End While
Loop While SQLdr.NextResult() 'Move to the Next Record
SQLdr.Close 'Close the SQLDataReader
SQLConn.Close() 'Close the connection

Related

How to update SQL Server table from Excel data

I've a vendor table in SQL Server with vendor code, vendor ID and vendor name. Another table called disc_mast with columns vendor ID and disc_per. Vendors will revise disc% frequently and we will get the details in Excel with vendor code and disc%. How can I update the discount percent in the disc_mast from the data in excel without importing the data in Excel to SQL Server tables.
You can do something like this.
Sub Update()
'Declare some variables
Dim cnn As adodb.Connection
Dim cmd As adodb.Command
Dim strSQL As String
'Create a new Connection object
Set cnn = New adodb.Connection
'Set the connection string
cnn.ConnectionString = "Your_Server_Name;Database=Northwind;Trusted_Connection=True;"
'Create a new Command object
Set cmd = New adodb.Command
'Open the connection
cnn.Open
'Associate the command with the connection
cmd.ActiveConnection = cnn
'Tell the Command we are giving it a bit of SQL to run, not a stored procedure
cmd.CommandType = adCmdText
'Create the SQL
strSQL = "UPDATE TBL SET JOIN_DT = 2013-01-13 WHERE EMPID = 2"
'Pass the SQL to the Command object
cmd.CommandText = strSQL
'Open the Connection to the database
cnn.Open
'Execute the bit of SQL to update the database
cmd.Execute
'Close the connection again
cnn.Close
'Remove the objects
Set cmd = Nothing
Set cnn = Nothing
End Sub
This is VBA code that runs in Excel. Also, create a reference to 'Microsoft ActiveX Data Objects x.x Library'.
Tools -. References:

Connect to SQL Server in VBA if the server requires specific username and password?

I realized today that when you connect to SQL Server data source in Excel's native connection, it doesn't allow you to enter in a specific username and password. It just asks for server name and database.
In VBA , under the assumption that I wanted to import data from a SQL Server data query into Sheet1, can you please help me understand how to write that code?
For purposes of this exercise:
SQL Server Connection INFO
Server Name: TestingS,1633
Database Name: CarSales
username: car
password: sales
The query I want to run for simplicity sake can be: "select * from table"
I have been doing some research , but am getting a bit lost. I have no problem setting up standard queries with custom SQL via ODBC, but because I need VBA, it's very tricky for me. Please help.
This is an example of MSSQL.
Sub testMSSQL()
'Reference Microsoft ActiveX data object Library 2.8 ~~
Dim cnn As ADODB.Connection
Dim strSQL As String
Dim Ws As Worksheet
Set Ws = ActiveSheet
strSQL = "select * from table"
Set cnn = New ADODB.Connection
'Set the provider property to the OLE DB Provider for ODBC.
'cnn.Provider = "MSDASQL"
'cnn.Provider = "Microsoft.ACE.OLEDB.12.0"
'cnn.Provider = "MSOLAP"
cnn.Provider = "SQLOLEDB.1" '<~~ mssql
' Open a connection using an ODBC DSN.
cnn.ConnectionString = "driver={SQL Server};" & _
"server=TestingS;uid=car;pwd=sales;database=CarSales"
Set rs = New ADODB.Recordset
rs.Open strSQL, cnn.ConnectionString, adOpenForwardOnly, adLockReadOnly, adCmdText
cnn.Open
If cnn.State = adStateOpen Then
Else
MsgBox "Not connected server"
Exit Sub
End If
If Not rs.EOF Then
With Ws
.Range("a1").CurrentRegion.ClearContents
For i = 0 To rs.Fields.Count - 1
.Cells(1, i + 1).Value = rs.Fields(i).Name
Next
.Range("a2").CopyFromRecordset rs
.Columns.AutoFit
End With
Else
MsgBox "No Data!!", vbCritical
End If
rs.Close
Set rs = Nothing
cnn.Close
Set cnn = Nothing
End Sub

Import data from Excel into SQL Server using queries

If I am not allowed to use the import function of SQL Server to bring data from Excel into SQL Server, would you be able to use queries to import the data?
There are several ways to export data from Excel to SQL Server. Here is one concept.
Sub InsertInto()
'Declare some variables
Dim cnn As adodb.Connection
Dim cmd As adodb.Command
Dim strSQL As String
'Create a new Connection object
Set cnn = New adodb.Connection
'Set the connection string
cnn.ConnectionString = "Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security Info=True;Initial Catalog=Northwind;Data Source=server_name"
'cnn.ConnectionString = "DRIVER=SQL Server;SERVER=server_name;DATABASE=Northwind;Trusted_Connection=Yes"
'Create a new Command object
Set cmd = New adodb.Command
'Open the Connection to the database
cnn.Open
'Associate the command with the connection
cmd.ActiveConnection = cnn
'Tell the Command we are giving it a bit of SQL to run, not a stored procedure
cmd.CommandType = adCmdText
'Create the SQL
strSQL = "UPDATE TBL SET JOIN_DT = '2013-01-22' WHERE EMPID = 2"
'Pass the SQL to the Command object
cmd.CommandText = strSQL
'Execute the bit of SQL to update the database
cmd.Execute
'Close the connection again
cnn.Close
'Remove the objects
Set cmd = Nothing
Set cnn = Nothing
End Sub

How do run a stored procedure from SQL in VBA and then paste the data into Excel?

So I am quite new to VBA but I need to write a VBA macro which runs the stored procedure in Microsoft SQL server and then paste this data into the excel worksheet.
So far this is the code that I have, but I am not sure how to proceed? Is there sample code or a template for this particular procedure?
Sub Connection() ' create the connection
loginstatus = True
login.Show
Password = login.password_input
user = login.UserName
Dim con As ADODB.Connection
Dim stored_procedure As String
Dim ADODBCmd As ADODB.Command
Dim rs As ADODB.Recordset
Set con = New ADODB.Connection
'provide and create connection string
Dim connectionString As String
Dim location As String 'the server
location = "MyLocation"
connectionString = "Provider=SQLOLEDB; Network Library=DBMSSOCN;Data Source=" & location & ";Command Timeout=0;Connection Timeout=0;Packet Size=4096; Initial Catalog=ukmc; User ID=" & user & "; Password=" & Password & ";"
'handle when it is not possible to log in
On Error GoTo ConnectionError
con.Open connectionString
loginstatus = False
Exit Sub
'errorhandl0
ConnectionError:
MsgBox "Not possible to log in. Have you entered the correct password?"
'recordset - the data extracted
Set ADODBCmd = New ADODB.Command
End Sub
So i think I have created the connection, but how do I tell it which stored procedure to run and then how do i paste the data into a worksheet in my excel document?
From the link
myConnection.Open
Set myCommand.ActiveConnection = myConnection
Set myRecordSet.ActiveConnection = myConnection
myCommand.CommandText = strSQL
myCommand.CommandType = adCmdText
myCommand.Execute
myRecordSet.Open myCommand
'Paste to spreadsheet
ThisWorkbook.Worksheets("Report").Range("a2").CopyFromRecordset
myRecordSet

SQL to VBA: Error importing table from SQL into excel

In the code below, I keep getting an error message saying:
"Runtime Error '-2147467259 (80004005)': Automation Error Unspecified
Error"
The error pops up when I try and open the connection. All I want to do is import data from a local SQL DB into excel.
I don't know if it matters, but I am using SQL server 2014 express.
Sub connect()
Dim conn As ADODB.Connection
Dim cmd As ADODB.Command
Dim rs As ADODB.Recordset
Dim strConn As String
Dim connstr As String
Dim strSRV As String
Dim strDB As String
Dim sql_login As String
sqlquery = "SELECT top 10 * FROM [Source Contacts];"
connstr = "Driver={SQL Server native Client 11.0};Server=(LocalDB)\v11.0;AttachDBFileName=C:\Program Files\Microsoft SQL Server\MSSQL10_50.SQLEXPRESS\MSSQL\DATA\SIT23DL_Validation.mdf;Database=SIT23DL_Validation;Trusted_Connection=Yes"
'Create the Connection and Recordset objects
Set conn = New ADODB.Connection
conn.ConnectionString = connstr
conn.Open
Set rs = conn.Execute(sqlquery)
If Not rs.EOF Then
'Transfer result
Sheets(1).Range("A1").CopyFromRecordset rs
'Close Recordset
rs.Close
Else
MsgBox "Error: No records returned.", vbCritical
End If
'Clean up
If CBool(conn.State And adStateopen) Then conn.Close
Set conn = Nothing
Set rs = Nothing
End Sub
Agreed with the comments, most likely culprit is the connection string. Try connecting to your SQL instance using 'Microsoft SQL Server Management Studio' and attach the database through that interface (not through the connection string). If all that works, you can try the following (you may need to replace localhost with your actual machine name):
connstr = "Provider=SQLOLEDB;Data Source='localhost\v11.0';Initial Catalog='SIT23DL_Validation';Integrated Security=SSPI;Trusted_Connection=Yes"

Resources