How to run a Stored Procedure which returns a dataset - sql-server

I have a simple stored procedure(Select Name,ID from MyTable) and I want to call it from C#(or VB.NET) to populate a dataset.
Here is my code:
Public Class PaymentDataAccess
Public Function GetPaymentData() As DataSet
Dim cn As New SqlClient.SqlConnection
cn.ConnectionString = "Data Source=WORK-HP\BTFSERVER1;Initial Catalog=PaymentReminder;Integrated Security=True"
Dim Cmd As New SqlCommand("GetPaymentData", cn)
Cmd.CommandType = CommandType.StoredProcedure
Dim sa As New SqlDataAdapter(Cmd)
cn.Open()
Dim ds As DataSet = Nothing
Try
sa.Fill(ds)
Catch ex As Exception
Dim i As Integer = 7
End Try
Return ds
End Function
End Class
I am getting an exception at sa.Fill(ds)
{"Value cannot be null.
Parameter name: dataSet"}
System.ArgumentNullException: {"Value cannot be null.
Parameter name: dataSet"}
Here is my stored procedure:
USE [PaymentReminder]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[GetPaymentData]
AS
BEGIN
SET NOCOUNT ON;
SELECT * from Payments
END

Just change this line from
Dim ds As DataSet = Nothing
to
Dim ds = new DataSet()
You need to pass an initialized DataSet to the SqlDataAdapter.Fill method.
Actually your code is like
sa.Fill(Nothing)
and of course this is not appreciated by the Fill code.

Related

How to Parameterized Queries with the SqlDataSource (VB)

This is my code example to run parameterized query in VB.NET:
Dim sqlconn As New SqlConnection(connectionString)
sqlconn.Open()
Dim cmd As New SqlCommand
cmd.CommandText = "Select * from TAble1 Where SkuCode in (#SKU)"
cmd.Connection = sqlconn
Dim parm As New SqlParameter
parm.Value ="1" 'This is working
parm.ParameterName = "#SKU"
cmd.Parameters.Add(parm)
Dim ds As New DataSet
Dim sqlDa As New SqlDataAdapter(cmd)
sqlDa.Fill(ds)
Dim dt As DataTable
dt = ds.Tables(0)
If dt.Rows.Count > 0 Then
MsgBox("Done")
Else
MsgBox("Not done.")
End If
If I run this example in VB.NET this returns the result successfully.
But there is an issue while trying to get results with multiple in records... this is not working.
Please check and suggest the change we have to do to run in query with parameters.
'parm.Value = "N'1', N'2'" 'this does not work.
'parm.Value = "'1','2'" 'this does not work.
I have tried these parameter value but it does not work.
SQL parameters are scalar and only accept a single value. You can use the sqldbtype.Structured though it gets a bit complicated.
I've found that if you need to pass in a set of parameters for an IN where the number of parameters is dynamics, the most effective way (unfortunately) is:
String interpolation/concatenation without parameters
Loop to build out the parameters and add them to your sqlcommand
LINQ to build out the parameters and add them to your sqlcommand
I've provided an example of the linq option below.
Dim sqlParams As Dictionary(Of String, Integer) = integers.ToDictionary(Function(i) $"#ParamValue{i}", Function(i) i)
Dim ds As New DataSet
Dim dt As DataTable
Using db as new SqlConnection(conn)
conn.open()
Using cmd As New SqlCommand($"SELECT * FROM Table1 WHERE SkuCode IN (-1, {String.Join(", ", sqlParams.Select(Function(f) f.Key))}", db)
cmd.Parameters.AddRange(sqlParams.Select(Function(f) New SqlParameter(f.Key, SqlDbType.BigInt).Value = f.Value).ToArray())
Dim sqlDa As New SqlDataAdapter(cmd)
sqlDa.Fill(ds)
dt = ds.Tables(0)
End Using
End Using
MsgBox(If(dt.Rows.Count > 0, "Done", "Not done"))

Getting data from a stored procedure

I have a stored procedure like this:
Select name, surname from student
and I can't get data with VB.Net.
My code is:
Dim reader As SqlDataReader
With dbCmd
.CommandType = CommandType.StoredProcedure
.CommandText = "sp_myPersonalSP"
End With
reader = dbCmd.ExecuteReader()
But Visual Studio send me an exception when it try "reader = dbCmd.ExecuteReader()":
Procedure sp_myPersonalSP has no parameters and arguments were supplied.
Thanks! I am a newbie in VB.Net :-(
A function that returns a datatable from Sql Server executing a stored procedure:
Public Function GetApplicationType() As DataTable
Dim MyDataTable As DataTable = New DataTable()
' The connection string information is in the web.config file - see below
Dim con = ConfigurationManager.ConnectionStrings("MyConnectionString").ToString()
Dim MyDataAdapter As SqlDataAdapter = New SqlDataAdapter("GetSomeData", con)
MyDataAdapter.SelectCommand.CommandType = CommandType.StoredProcedure
' add the parameters in the same order and type as what the stored procedure expects, they must match the names in the stored procedure and are case sensitive.
MyDataAdapter.SelectCommand.Parameters.Add(new SqlParameter("#ParameterName", SqlDbType.VarChar, 10));
MyDataAdapter.SelectCommand.Parameters.Add(new SqlParameter("#Parametername2", SqlDbType.VarChar, 40));
MyDataAdapter.SelectCommand.Parameters["#ParameterName"].Value = somedata1;
MyDataAdapter.SelectCommand.Parameters["#ParameterName2"].Value = somedata2;
MyDataAdapter.Fill(MyDataTable)
Return MyDataTable
End Function
web.config
<connectionStrings>
<add name="MyConnectionString" connectionString="server=192.168.11.11;database=Test;uid=someusername; pwd=somepassword" providerName="System.Data.SqlClient" />
</connectionStrings>
You can display your query results in a DataGridView. You need to have a connection for the command to execute. Open the connection before you execute the command. The Using...End Using statements with ensure that your objects are closed and disposed event if there is an error.
Private Sub GetData()
Using cn As New SqlConnection("Your Connection String")
Using dbCmd As New SqlCommand
With dbCmd
.CommandType = CommandType.StoredProcedure
.CommandText = "sp_myPersonalSP"
.Connection = cn
End With
cn.Open()
Using reader As SqlDataReader = dbCmd.ExecuteReader()
'You can view the result of your query in a DataGridView
Dim dt As New DataTable
dt.Load(reader)
DataGridView1.DataSource = dt
End Using
End Using
End Using
End Sub
to retrieve data from stored procedure, just call your stored procedure name like this.
Dim stringquery = "CALL YOURSTOREDPROCNAME()"
Try my Code:
Dim dt as new Datatable
con.Open()
Dim query = "Call StoredProcedureName()"
command = New SqlCommand(query, con)
adapter.SelectCommand = command
dt.Clear()
adapter.Fill(dt)
con.Close()
-KEVIN

loading xml file to stored procedure

I am trying to insert data from Xml file using a stored procedure, stored procedure as below :
CREATE PROCEDURE xmlreadtest
#xmldoc xml
AS
BEGIN
INSERT INTO Page (KeyId)
SELECT [Key].value('#Id[1]', 'VARCHAR (100)')
FROM #xmldoc.nodes('//Page/Key') AS TEMPTABLE([Key])
END
And Visual Basic calling the procedure :
Function ModfiyData()
Dim xmldocM As New XmlDocument
xmldocM.Load("C:\20170326.66.xml")
Dim SQLComm As New SqlCommand
Dim dbconn As New SqlConnection(con)
dbconn.Open()
SQLComm.Connection = dbconn
SQLComm.CommandText = "xmlreadtest"
SQLComm.CommandType = CommandType.StoredProcedure
SQLComm.Parameters.AddWithValue("#xmldoc", xmldocM)
SQLComm.ExecuteNonQuery()
dbconn.Close()
End Function
When i run the application it give error:
No mapping exists from object type System.Xml.XmlDocument to a known managed provider native type.
Any idea how can i solve this issue..
i am using vb 2015 and sql database file.
Try Casting XmlDocument to SqlXML
Dim xmldocM As New XmlDocument
xmldocM.Load("C:\20170326.66.xml")
Dim sw as new StringWriter()
Dim xw as new XmlTextWriter(sw)
xmldocM.WriteTo(xw)
Dim transactionXml as new StringReader(sw.ToString())
Dim xmlReader AS new XmlTextReader(transactionXml)
Dim XmlParamValue as new SqlXml(xmlReader)
Dim SQLComm As New SqlCommand
Dim dbconn As New SqlConnection(con)
dbconn.Open()
SQLComm.Connection = dbconn
SQLComm.CommandText = "xmlreadtest"
SQLComm.CommandType = CommandType.StoredProcedure
SQLComm.Parameters.AddWithValue("#xmldoc", XmlParamValue )
SQLComm.ExecuteNonQuery()
dbconn.Close()

Return result set from SQL Server stored procedure to vb.net

The following stored procedure works as I want in the Visual Studio designer. The result is a table containing all the race distances for the input #CourseName
ALTER PROCEDURE [dbo].[getCourseDistancesProc]
#CourseName nvarchar(50)
AS
BEGIN
SET NOCOUNT ON;
SELECT DISTINCT
RaceDistances.RaceDistance
FROM
RacingMaster
JOIN
RaceDistances ON RacingMaster.Dist_Of_Race_FK = RaceDistances.PKRaceDistancesId
JOIN
Courses ON RacingMaster.RM_Course_FK = Courses.PKCourseId
WHERE
CourseName = #CourseName
END
I want to call the stored procedure from a vb.net application. What data type do I declare as the output variable so that the full result set is returned to the calling app?
There was obviously more work to be done than I had realized, but just in case anyone else stumbles across this question the solution I finally adapted from elsewhere is:-
Dim myConn As SqlConnection
Dim myCmd As SqlCommand
Dim results As String
Dim ConnectionString As String
' Create the connection string.
ConnectionString = "Data Source=*********;" & _
"Initial Catalog=*******;" & _
"Integrated Security=SSPI;"
myConn = New SqlConnection(ConnectionString)
myConn.Open()
Dim InputName As String
InputName = TextBox1.Text
myCmd = New SqlCommand()
myCmd.CommandText = "getCourseDistancesProc"
myCmd.CommandType = CommandType.StoredProcedure
myCmd.Parameters.AddWithValue("#CourseName", Odbc.OdbcType.NVarChar).Value = InputName
myCmd.Connection = myConn
Dim myReader As SqlDataReader = myCmd.ExecuteReader()
If myReader.HasRows Then
Do While myReader.Read()
Dim var As String
var = myReader.GetString(0)
MsgBox(var)
Loop
Else
MsgBox("No rows found.")
End If
myReader.Close()
Obviously, the above is just to demonstrate that the requested data is indeed coming back from the database. But now I know that it is I can handle it in a more useful way.

vb.net Procedure or function expects parameter, which was not supplied

I am receiving this error:
Procedure or function 'usp__SingleSelectServerRackName' expects parameter '#chvServerName', which was not supplied.
I looked up the error and did not find any applicable solutions.
I was successfully able to run the Proc and retrieve out put information, and was able to successfully retrieve value of cbserver.valuemember in command window.
Any suggestions to correct this problem?
Here is my code:
Imports System.Data.SqlClient
Try
Dim connString As String = "server=ServerName;database=DatabaseName;trusted_connection=yes"
Using connection As New SqlConnection(connString)
'Create the command and set its properties.
Dim SingleSelectServerRackName As SqlCommand = New SqlCommand
SingleSelectServerRackName.Connection = connection
SingleSelectServerRackName.CommandText = "usp__SingleSelectServerRackName"
SingleSelectServerRackName.CommandType = CommandType.StoredProcedure
'Add the input parameter and set its properties
Dim ParamSingleSelectServerName As New SqlParameter()
ParamSingleSelectServerName.ParameterName = "#chvServerName"
ParamSingleSelectServerName.SqlDbType = SqlDbType.VarChar
ParamSingleSelectServerName.Direction = ParameterDirection.Input
ParamSingleSelectServerName.Value = cbServer.SelectedValue.ToString()
Dim ParamSingleSelectServerRackName As New SqlParameter
ParamSingleSelectServerName.ParameterName = "#numServerRackName"
ParamSingleSelectServerRackName.SqlDbType = SqlDbType.VarChar
ParamSingleSelectServerRackName.Direction = ParameterDirection.Output
ParamSingleSelectServerRackName.Size = 50
'Add the parameters to the Parameters collection
SingleSelectServerRackName.Parameters.Add(ParamSingleSelectServerName)
SingleSelectServerRackName.Parameters.Add(ParamSingleSelectServerRackName)
'Open database connection
connection.Open()
'Execute data reader
Dim readerSingleSelectServerRackName As SqlDataReader = SingleSelectServerRackName.ExecuteReader()
readerSingleSelectServerRackName.Close()
cbRackName.ValueMember = SingleSelectServerRackName.Parameters("#numServerRackName").Value.ToString
'Close database connection
connection.Close()
End Using
Catch ex As Exception
MsgBox(ex.Message)
MsgBox(ex.StackTrace)
End Try
Proc:
CREATE Procedure usp__SingleSelectServerRackName
(
#chvServerName AS varchar(50), ---Input variable #chvServerName displays
#numServerRackName AS varchar(50) OUTPUT ---Output variable #numServerRackName
)
AS Begin
IF #chvServerName is null or len(ltrim(#chvServerName)) = 0 ---Check for null value
RAISERROR('Servername cannot be blank.',16,1)
SELECT Rcknm.nm
FROM Rcknm
INNER JOIN Srvr
on srvr.fk_rcknm = Rcknm.ID
WHERE srvr.nm = #chvServerName
End
Looks like you missed something on your copy/paste of parameters.
ParamSingleSelectServerName.ParameterName = "#numServerRackName"
ParamSingleSelectServerName.ParameterName = "#chvServerName"
Your second parameter is overwriting your first. Try this instead.
ParamSingleSelectServerRackName.ParameterName = "#numServerRackName"
Name of the 2nd parameter is same so overwriting it
Look at these two lines
Dim ParamSingleSelectServerRackName As New SqlParameter
ParamSingleSelectServerName.ParameterName = "#numServerRackName"
You are declaring the second parameter, but then you set the name intended for the second parameter to the first parameter.
That's the missing parameter, you have no more a parameter called #chvServerName
You are really making your life difficult. Why not just calling the twos #Rack and #Server ?

Resources