SQL Stored Proc and Dataset - sql

I've got a sql stored proc that is working fine in SSMS. When I try and execute through code and assign the return to a dataset I am getting zero rows back. I've used the immediate window to ensure that I am sending the correct params to the stored proc and that is all good.
What else would cause me to get zero rows assigned to the dataset. Here is my code.
Thanks,
Mike
EDIT: I'm not getting any exceptions from SQL..
Public Function GetTransReporting(ByVal transNumber As Long, ByVal customerID As Long) As DataCommon.transReporting
Dim myTransReporting As New transReporting
Dim da As SqlDataAdapter
Dim prm1 As SqlParameter
Dim prm2 As SqlParameter
mcmd = New SqlCommand
mcmd.CommandType = CommandType.StoredProcedure
mcmd.Connection = mcn
mcmd.CommandText = "GetTransReportingByCustomerID"
prm1 = New SqlParameter("#transNumber", Data.SqlDbType.BigInt)
prm1.Value = customerID
mcmd.Parameters.Add(prm1)
prm2 = New SqlParameter("#customerNumber", Data.SqlDbType.BigInt)
prm2.Value = transNumber
mcmd.Parameters.Add(prm2)
da = New SqlDataAdapter(mcmd)
da.Fill(myTransReporting)
Return myTransReporting
End Function

Got it.. if you take a look at my parameters up top I am accidentally assigning transaction to customer and customer to transaction. DOH!
Thanks,
Mike

Does your stored procedure start with SET NOCOUNT ON? The lack of this can sometimes cause issues if the stored procedure is processing multiple queries before the final SELECT.

Related

adding sqlparameter without name

I'm trying to create a sub to add as many parameters as I want, I used to do this in vb6 but here in vb.net it requires me to provide the parameter name (.add(#parameter, value)). I need to find a way to do it without knowing the parameter name, i used to send the parameters using the parameter order in the stored procedure, here the code:
Public Sub EjecutarSP(ByVal SP As String, ByVal ParamArray Parametros() As Object)
Dim cnn As New SqlConnection(ConfigurationSettings.AppSettings("connString").ToString)
Dim cmd As New SqlCommand(SP, cnn)
Dim i As Integer
Dim Param As SqlParameter
Try
For i = 0 To UBound(Parametros)
Param = New SqlParameter("str", Parametros(i))
cmd.Parameters.Add(Param)
Next
cmd.CommandTimeout = 0
cmd.CommandType = CommandType.StoredProcedure
If cmd.Connection.State <> ConnectionState.Open Then cmd.Connection.Open()
cmd.ExecuteNonQuery()
cmd = Nothing
Catch ex As Exception
Err.Raise(1000, "EjecutarSP", ex.Message)
End Try
End Sub
thanks
AFAIK the SqlClient doesn't support nameless parameters
From here:
Nameless, also called ordinal, parameters are not supported by the .NET Framework Data Provider for SQL Server.
However, instead of explicitly creating the parameters, you could fetch the parameters for the Proc with DeriveParameters, once you are connected.
Assuming you wish to blindly wish to trust the order of the parameters to match the parameters of the Proc, simply set the .Value of the parameters at the given index.
Dim cmd As New SqlCommand(SP, cnn)
...
SqlCommandBuilder.DeriveParameters(cmd)
For i = 0 To UBound(Parametros)
cmd.Parameters(i).Value = Parametros(i)
Next
Just reset the name to nothing (null) once the parameter has been added, something like this:
For i = 0 To UBound(Parametros)
Param = New SqlParameter("str", Parametros(i))
cmd.Parameters.Add(Param)
Param.ParameterName = Nothing
Next
You don't have to explicity name or type parameters. There are actually a couple of ways to execute stored procs without naming each parameter. Here is one way using Microsoft's old EnterpriseLibrary (which I still like in 2019).
NB: in VB.NET the size of the parameter array is one less than the number of parameters in the stored proc.
Dim dt As System.Data.DataTable
Dim arrParameters(6) As Object
arrParameters(0) = "Hello"
arrParameters(1) = "World"
arrParameters(2) = "Lorem"
arrParameters(3) = "Ipsum"
arrParameters(4) = "Dolor"
arrParameters(5) = "Blabla"
arrParameters(6) = 12345
Try
Dim db As Microsoft.Practices.EnterpriseLibrary.Data.Database = Microsoft.Practices.EnterpriseLibrary.Data.DatabaseFactory.CreateDatabase("TheNameOfYourConnectionStringInWebConfig")
dt = db.ExecuteDataSet("TheNameOfYourStoredProcedure", arrParameters).Tables(0)
Catch ex As Exception
End Try

Execute Sybase SQL Stored Procedure With Return In VB

I'm trying to integrate with an application using Sybase as its backend. The application has a stored procedure for return the next primary key:
declare #key int
execute #key = GetNextPrimary('quotehdr')
select #key
If i execute the above from SQL Interactive #key comes back with the value. Now i need to execute the stored procedure and get the returned value from VB. Initially I thought there must be a way of executing the stored procedure by reformatting the SQL command into a single line statement however after reading other posts it's clear that I'll need to use the CommandType.StoredProcedure method however I'm struggling with the syntax for the parameters and getting the response:
Try
conn.Open()
cmd.Connection = conn
cmd.CommandText = "GetNextPrimary"
cmd.CommandType = CommandType.StoredProcedure
cmd.Parameters.AddWithValue("#key", "quotehdr")
Dim lrd As Odbc.OdbcDataReader = cmd.ExecuteReader()
While lrd.Read()
QuoteHdrRef = Convert.ToString(lrd(0))
End While
Catch ex As Exception
'MessageBox.Show("Failed to connect to data source")
Finally
conn.Close()
End Try
Can anyone give me and pointers
Thanks in advance
Vince
You don't need to pass any parameter if the stored procedure has the text written in your question.
The #Key is an internal declaration of a variable, it is not a parameter.
It is returned by the DataReader as a table of a single row with a single column.
Just remove the line that adds the parameter and you are fine.
And don't swallow the exceptions in that way. If you don't plan to do something with the exception, then remove the Catch or (for debugging purpose) just show the ex.Message property
Turns out GetNextPrimary was a function. So used a procedure (getnextprimaryproc) to call the function:
ALTER PROCEDURE "DBA"."getnextprimaryproc"(in tablename varchar(128),out ll_primary integer)
begin
ll_primary=call "dba".getnextprimary(tablename)
end
Then used the following in VB to call
cmd.Connection = conn
cmd = New Odbc.OdbcCommand("{ call getnextprimaryproc (?, ?)}", conn)
Dim param As Odbc.OdbcParameter = cmd.Parameters.Add("#tablename", Odbc.OdbcType.VarChar)
param.Value = "quotehdr"
param = cmd.Parameters.Add("#ll_primary", Odbc.OdbcType.Int)
param.Direction = ParameterDirection.Output
conn.Open()
cmd.ExecuteNonQuery()
QuoteHdrRef = cmd.Parameters(1).Value

SQLDataReader not reading using VB.net

I am using a SQLDataReader to display the results of my stored procedure, however, I have been unable to have it display any records. I am not generating an error and if I write out reader.hasrows.tostring() it returns true so I know it is returning a single row as intended. I know I have data in all columns to display. Any guidance would be appreciated.
Dim sqlcon2 As SqlConnection = New SqlConnection(Session("ConnStrEP"))
sqlcon2.Open()
Dim sqlcomm2 As SqlCommand = New SqlCommand("up_GetGenInfo_E1_01_02", sqlcon2)
sqlcomm2.CommandType = Data.CommandType.StoredProcedure
sqlcomm2.Parameters.Add("AppNo", AppNo)
sqlcomm2.Parameters.Add("RevNo", RevNo)
Dim dt As SqlDataReader = sqlcomm2.ExecuteReader()
dt.Read()
Response.Write(dt.Item("PrName").ToString())
dt.Close()
sqlcomm2.Dispose()
sqlcon2.Close()
Do it in a following way:
Do While dt.Read()
Response.Write(dt.Item("PrName").ToString())
Loop

Calling Stored Procedures from VB.NET

Can anyone please help me on the following:
I have created a SQL Server stored procedure as follows:
create procedure prcGet_sub_menu_list
#sub_menu char(5)
as
begin
select
'menu_code' = menu_code
'menu_name' = menu_name
from sub_menu_master
where menu_code = #sub_menu
end
return
Now i am calling this procedure from VB.NET, but i get an error like 'Stored procedure prcGet_sub_menu_list expects parameter #sub_menu which was not supplied'. Please help me on the same. The code which i have in VB.NET is as follows:
Imports System.Data
Imports System.Data.SqlClient
Dim sqlConn as New SqlClient.SqlConnection
sqlConn.ConnectionString = "........"
sqlConn.Open()
Dim menuCode as string
menuCode = cboDetails.selectedItem
Dim sqlCmd as New SqlCommand
sqlCmd.Connection = Connection.sqlConn
sqlCmd.CommandType = CommandType.StoredProcedure
sqlCmd.CommandText = "prcGet_sub_menu_list"
sqlCmd.Parameter.Add("menuCode", SqlDbType.Char)
Dim sqlDA as New SqlDataAdapter()
sqlDA.SelectCommand = sqlCmd
Dim sqlDT as New DataTable
sqlDA.Fill(sqlDT)
This is the code that i have written and it gives me the error:
'Stored procedure prcGet_sub_menu_list expects parameter #sub_menu which was not supplied'.
Please give me some help on the same.
Regards,
George
You have to give the same parameter name and type like in your stored procedure.
sqlCmd.Parameters.Add(New SqlParameter("#sub_menu", SqlDbType.Char, 5)).Value = "Joe"
Geetha.
As the message implies, you should add a parameter named "sub_menu" in the same way as you're adding the "menuCode" parameter. You should probably also give it a value:
sqlCmd.Parameter.Add("sub_menu", SqlDbType.Char).Value = "Blah"
(Of course, I don't know what the correct type is, so Char is just an example.)
You need to use the correct parameter name
Something like
sqlCmd.Parameter.Add("#sub_menu", SqlDbType.Char)
And assign it a value
Something like
sqlCmd.Parameters("#sub_menu").Value = val
Have a look at SqlCommand.Parameters Property
and maybe Lesson 07: Using Stored Procedures
A couple things. Parameter should be Parameters. Also sqlCmd.Parameters.Add is deprecated so use sqlCmd.Parameters.AddWithValue:
sqlCmd.Parameters.AddWithValue("menuCode", menuCode)

How to check if Current ID exits in that table or not

I am using VB.net and Sql server 2005.
I have GridView in Application where I have my CPUserID. There can be thousands records in GridView with different CPUserIDs.
Now I have a button "Allocate Token". But before allocating the token I want to check in my Token Table that if that CPUserID has already exists in table it should not allow user to allocate token and will return some message for that user.
For Each curRow As GridViewRow In GridView1.Rows
Dim cpuserid As Label = CType(curRow.Cells(1).FindControl("lblCPUserID"), Label)
Next
The TOKEN table structure is given below:
TokenID, CPUserID, StatusID (All Integer)
Please Suggest! with some example code
Perform a query on the Token table to see if there already exists a row in that table for the given id:
SELECT COUNT(*) FROM Token WHERE CPUserID = 5
for instance.
In order to do that in VB.NET, you'll have to use the SqlConnection and SqlCommand classes.
Also, be sure to make use of parameterized queries.
In C#, the code would look more or less like this:
SqlConnection conn = new SqlConnection ("here comes the connectionstring to the db.");
conn.Open();
try
{
SqlCommand cmd = new SqlCommand ();
cmd.Connection = conn;
cmd.CommandText = "SELECT COUNT(*) FROM Token WHERE CPUserId = :p_UserId";
cmd.Parameters.Add ("p_UserId", SqlDbType.Int32).Value = 5;
object result = cmd.ExecuteScalar();
if( Convert.ToInt32(result) > 0 )
{
MessageBox.Show ("Token already exists for user");
}
}
finally
{
conn.Close();
}
In order to improve performance, you will have to make sure that you create the correct indexes on the Token table.
An index on CPUserId would maybe help for this query.
First of all thanks to all of them who responded for this question.
I solved above issues with below solutions:
SQL Procedure:
I created one procedure in SQL server 2005
GO
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[uspUpdateAllocateToken]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[uspUpdateAllocateToken]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[uspUpdateAllocateToken]
( #CPUserID INT)
AS
IF NOT EXISTS(SELECT TokenID FROM tblToken WHERE CPUserId=#CPUserID AND StatusID IN (41,47))
BEGIN
UPDATE tblToken
SET
CPUserID = #CPUserID,
StatusID=47
WHERE
tblToken.TOKENID = (SELECT TOP 1 TOKENID FROM TBLTOKEN WHERE CPUSERID IS NULL AND STATUSID = 40)
END
Further in my application on my Button Click. I write below code:
Protected Sub ibtnAllocateTokens_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles ibtnAllocateTokens.Click
Try
Dim conString As String = WebConfigurationManager.ConnectionStrings("LocalSqlServer").ConnectionString
Dim con As New SqlConnection(conString)
con.Open()
Dim cmd As SqlCommand
For Each gvRow As GridViewRow In GridView1.Rows
cmd = New SqlCommand("uspUpdateAllocateToken", con)
cmd.CommandType = CommandType.StoredProcedure
cmd.Parameters.Add("#CPUserID", SqlDbType.Int).Value = CType(gvRow.Cells(1).FindControl("lblCPUserID"), Label).Text
cmd.ExecuteScalar()
lblAllocateTokenMessage.Visible = True
Next
Catch ex As Exception
ErrorHandler.WriteError(ex.Message)
End Try
End Sub
Please have a look and let me know if there seems any problem in this implementation.
Cheers!