SqlClient.SqlCommand Bombing Out - asp.net

Still new to .NET, but this looks OK to me. I can't figure out what's going on. I'm trying to add 1 parameter to a SqlCommand. It is an integer in SQL Server, and I'm passing an integer to it.
It hangs on the Command.Parameters.Add(PolicyNo) code line and kicks out an "unable to process due to internal error".
I've also tried
Command.Parameters.AddWithValue("#PolicyNumber", PolicyNo)
But to no avail. It bombs out with the same error message. Here's the code:
Public Function GetPolicyObj(ByVal PolicyNo As Integer) As PolicyInfo Implements ILetterWriter.GetPolicyObj
Dim SQLcon As New SqlClient.SqlConnection
'Establish the connection
SQLcon.ConnectionString = "Data Source=Hosed;Initial Catalog=MyCat;User ID=Goofy;Password=OpenSesame;"
SQLcon.Open()
Using Command As New SqlClient.SqlCommand("sp_GetPolicyInfo", SQLcon)
Command.CommandType = CommandType.StoredProcedure
Command.Parameters.Add(PolicyNo) 'Bombs on this line
Command.Connection.Open()
Dim reader As SqlClient.SqlDataReader = Command.ExecuteReader
Any Ideas?
Thanks,
Jason

Have you tried creating the parameter like this:
Dim param as new SqlParameter()
param.ParameterName = "ParamName"
param.Value = PolicyNo
Command.Parameters.Add(param)

Not entirely sure if this is the problem should be, but you are not giving the parameter object a name, only passing the value which will thrown an exception, you have to give the parameter a name as well
Command.Parameters.Add(new SqlParameter("PolicyNo",PolicyNo))

Command.Parameters.Add() takes a SqlParameter object as its parameter. So you can't just send the integer.
http://www.csharp-station.com/Tutorials/AdoDotNet/Lesson06.aspx

Try:
Command.Parameters.AddWithValue("#PolicyNo", PolicyNo);

Maybe you could try explicitly typing your parameter:
Command.Parameters.Add("#PolicyNumber", SqlDbType.Int)
Command.Parameters("#PolicyNumber").Value = PolicyNo
And make sure your parameter name and datatype match what's in the stored procedure.

Related

Execute Scalar to Label. Subquery returned more than 1 value

So I have a label which shows the username of the user. I've used this value to return their ID which I then attach to a label. I used execute scalar to do this because I wasn't sure how else to get a single value on a label.
This works fine. I then use the ID from the label and put it in another table. I can do this twice and then the page crashes saying...
"Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression."
However I don't understand. I don't pull anything from the second table on the page. I don't know why it would affect it. I feel like I've tried everything. Taking out the line that posts the ID to the label lets the page run but I need it there.
Label2.Text = User.Identity.Name
Dim connetionString As String
Dim cnn As SqlConnection
Dim cmd As SqlCommand
Dim sql As String
connetionString = "Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\FYPMS_DB.mdf;Integrated Security=True"
sql = "SELECT SupID FROM Supervisor WHERE (Email = #Email)"
cnn = New SqlConnection(connetionString)
Try
cnn.Open()
cmd = New SqlCommand(sql, cnn)
cmd.Parameters.Add(New SqlParameter("#Email", User.Identity.Name))
Dim supid1 As Int32 = Convert.ToInt32(cmd.ExecuteScalar())
cmd.Dispose()
cnn.Close()
Label1.Text = supid1.ToString
Catch ex As Exception
MsgBox("Can not open connection ! ")
End Try
End Sub
This should return the first result for you. Also, it's a good idea to employ Using blocks for objects such as connections, commands, and readers.
Using cn = New SqlConnection("Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\FYPMS_DB.mdf;Integrated Security=True")
cn.Open()
Using cmd = New SqlCommand("SELECT SupID FROM Supervisor WHERE Email = #Email", cn)
cmd.Parameters.AddWithValue("#Email", User.Identity.Name)
Using dr = cmd.ExecuteReader
If dr.Read Then
Label1.Text = CInt(dr("SupID"))
End If
End Using
End Using
End Using
If you are not sure there are multiple rows for same email in that table, you can change the query to following, that will work for you with executescalar.
SELECT TOP 1 SupID FROM Supervisor WHERE (Email = #Email)
Horribly sorry! But yes you were right! There was another query going on in the background that I never noticed that was affecting it all. So sorry

SQLClient output parameter returns DBNull

Its a ASP.net application in VS2008, connecting to SQL 2005 database.
No errors calling the Stored procedure, db update is successful but the OUTPUT param returns DBnull all the time. Below the vb code:
Dim ConnectString As String = "", connect As New Data.SqlClient.SqlConnection
ConnectString = ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString
connect.ConnectionString = ConnectString
Dim cmd As New SqlCommand("saveAccess", connect)
cmd.CommandType = CommandType.StoredProcedure
cmd.Parameters.Add(New SqlParameter("#Name", "SampleName"))
Dim outparam As SqlParameter = New SqlParameter("#returnValue", SqlDbType.Int)
outparam.Direction = ParameterDirection.Output
cmd.Parameters.Add(outparam)
connect.Open()
cmd.ExecuteNonQuery()
If IsDBNull(cmd.Parameters("#returnValue").Value Then
Response.Write("Why does it always returns DBNull")
Else : Response.Write(cmd.Parameters("#returnValue").Value.ToString())
End If
connect.Close()
Here is the SQL code
ALTER PROCEDURE [dbo].[saveAccess]
(#Name NVARCHAR(20), #returnValue INT OUTPUT )
AS
BEGIN
INSERT INTO Access ([Name]) VALUES (#Name);
SELECT #returnValue = ##ROWCOUNT;
END
Not sure what is the silly mistake that I am doing. Any input helps.
Thanks
Instead of SELECT, try using SET to set the value of the output parameter
SET #returnValue = ##ROWCOUNT;
Solution (as said silly myself): missed the # symbol in front of the returnValue variable. I typed up the code in this posting correctly but I had it without the # in the SP.
wrong: SELECT returnValue = ##ROWCOUNT;
correct: SELECT #returnValue = ##ROWCOUNT;
Thanks

VB.NET ORA-01745: invalid host/bind variable name

For the last 2 hours I was trying figure out why the parameter could not be bound (Well I know I was not using the "using" block. And I know System.Data.OracleClient is deprecated.) Please help me see what's wrong with the following code:
Dim nCount As Integer
sSQL = " SELECT COUNT(*) FROM USERS WHERE USER_ID = :UID "
Dim conn As OracleConnection = New OracleConnection(ConfigurationSettings.AppSettings("connString"))
conn.Open()
Dim cmd As OracleCommand = New OracleCommand(sSQL, conn)
cmd.CommandType = CommandType.Text
With cmd
.Parameters.Add(New OracleParameter(":UID", txtUserID.Text))
End With
Try
nCount = cmd.ExecuteScalar()
Catch ex As Exception
End Try
I have tried all variations I can find online: with or without colon in the Parameters.Add, Add or AddWithValue, Add in a parenthesis or create a new OracleParameter object then add it...Nothing seems to work.
But if I just hard-code the USER_ID in the query, remove the parameter.Add, it would return a value.
A HA!
UID is actually a reserved word in Oracle. Change your UID variable to something that is not a reserved word.
For me it seems that you missed something, while experimenting with different combinations.
This variant must work:
Dim nCount As Integer
sSQL = "SELECT COUNT(*) FROM USERS WHERE USER_ID = :UID"
Dim conn As OracleConnection = New OracleConnection(ConfigurationSettings.AppSettings("connString"))
conn.Open()
Dim cmd As OracleCommand = New OracleCommand(sSQL, conn)
cmd.CommandType = CommandType.Text
cmd.Parameters.Add("UID", OracleType.VarChar).Value = txtUserID.Text
nCount = cmd.ExecuteScalar()
Please try it ...
Do yourself a favor and at least look into ODP from Oracle. You'll need it with Microsoft finally pulls the plus on its OracleClient. The switch over to ODP is very easy.
In your situation, I'd leave off the parameter name. You're binding by position anyway.
The SQL syntax is also a little different in the Microsoft implementation. Use a ? to act as each placeholder. See http://msdn.microsoft.com/en-us/library/system.data.oracleclient.oracleparameter.aspx for further information.

escaping apostrophes with parameter query not working

I am trying to prevent from having to escape apostrophes in my string variables by using a parameterized query with a OleDbConnection, but it is not working. any help would be appreciated. I am trying to insert into an Access db and I keep getting those pesky html codes.
Any hep would be appreciated.
Dim pConn As New OleDb.OleDbConnection
pConn = New OleDbConnection(cb.ConnectionString)
Dim SqlString As String = "INSERT INTO Strings (Mlt_String_ID, Lng_ID, Strg_Name, Sht_Text, Lng_Text, Alt_Text) Values (#Mlt_String_ID,#Lng_ID,#Strg_Name,#Sht_Text,#Lng_Text,#Alt_Text)"
Using cmd As New OleDbCommand(SqlString, pConn)
cmd.CommandType = CommandType.Text
cmd.Parameters.AddWithValue("#Mlt_String_ID", Mlt_String_ID)
cmd.Parameters.AddWithValue("#Lng_ID", Lng_ID)
cmd.Parameters.AddWithValue("#Strg_Name", Strg_Name)
cmd.Parameters.AddWithValue("#Sht_Text", Sht_Text)
cmd.Parameters.AddWithValue("#Lng_Text", Lng_Text)
cmd.Parameters.AddWithValue("#Alt_Text", Alt_Text)
pConn.Open()
cmd.ExecuteNonQuery()
pConn.Close()
End Using
ou didn't describe what "not working" means. Can you provide more information? Are you getting an exception? What is the exception and stack trace?
In any event, the OleDb commands do not support named parameters. Use question marks instead:
Dim SqlString As String = "INSERT INTO Strings (Mlt_String_ID, Lng_ID, Strg_Name, Sht_Text, Lng_Text, Alt_Text) Values (?,?,?,?,?,?)"
And the parameters must be added in order.

Returning date from Stored procedure in ASP.Net/VB.Net

I want to execute a method on VB.Net to return a date which is in the stored procedure. I tried using ExecuteScalar but it doesnt work it retruns error
'Implicit conversion from data type datetime to int is not allowed. Use the CONVERT function to run this query'
Any help would be much appreciated please?
thank you
below is the code
Public Function GetHolidaydate(ByVal struserID as String) As DateTime
Dim objArgs1 As New clsSQLStoredProcedureParams
objArgs1.Add("#userID", Me.Tag)
objArgs1.Add("#Date", 0, 0, ParameterDirection.Output)
Return (CDate(ExecuteScalar(clsLibrary.MyStoredProcedure.GetHolidayDate, objArgs1)))
End Function
I think that your problem is here:
objArgs1.Add("#Date", 0, 0, ParameterDirection.Output)
You are adding 0's where they should be typeOf DateTime.
EDIT
Public Function GetHolidayDate(ByVal struserID as String) AS DateTime
Dim con As New SqlConnection(yourSQLConnectionString)
Dim cmd As New SqlCommand
Dim date As DateTime
con.Open()
cmd.Connection = con
cmd.CommandType = CommandType.StoredProcedure
cmd.CommandText = "yourStoredProcedureName"
cmd.Parameters.Add("#userID", Me.Tag)
cmd.Parameters("#Date").Direction = ParameterDirection.Output
cmd.ExecuteScalar()
date = cmd.Parameters("#Date").Value
con.Close()
Return date
End Function
Looks like the error you are getting is a SQL error not a VB.Net error. Are you trying to convert a datetime to an int somewhere?
You could you try running the ExecuteNonQuery() method to see if you get the same error.
You could also run SQLProfiler and see exactly what SQL is being run.
You could then try running this SQL is SQL Server Management Studio
You add two parameters - but you said it should return the later one ?
So it must be
date DateTime = cmd.ExecuteScalar()
REM date = cmd.Parameters("#Date").Value
con.Close()

Resources