Monday, March 12, 2012

How to return a string from a Stored Procedure

Up till now I've used SP's for updates and only ever needed to return error messages.

Now I have an SP that checks and validates something and has to return a string containing the result, (always a string/varchar!)

It works fine in Query Analyzer, I just need a demo of how to incorporate it into a VB app.

Hope that makes sense.

Thanks
Markuse OUTPUT Parameters...check BOL for more info..

hth|||Thanks, I already have that.

My question was how to return it into VB.Net|||if you mean how to catch the returned value from vb.net


...
'output parameter
myParam = mycommand.CreateParameter()
myParam.ParameterName = "@.result"
myParam.Direction = ParameterDirection.Output
myParam.SqlDbType = SqlDbType.varchar
mycommand.Parameters.Add(myParam)

mycommand.ExecuteNonQuery()
return convert.todouble((mycommand.Parameters("@.result").Value))
objcon.close
...

hth|||OK, I got what I wanted.

I hadn't thought of using ExecuteScalar with a SP, just needed to broaden my thinking a bit.

so...abbreviated...here's what I did.

Dim con as New SqlConnection("myConnectionString")
Dim cmd = New SqlCommand("mySPname",con)
cmd.CommandType=CommandType.StoredProcedure
cmd.Parameters.Add("@.ItemID",12345)
" " "
" " "
Try
cmd.Connection = con
cmd.Connection.Open()
x = cmd.ExecuteScalar()
Catch exp As SqlException
x = exp.Message
Finally
cmd.Collnection.Close()
End Try

This way I either get the string value I was looking for or the error message.

No comments:

Post a Comment