SqlCommand.ExecuteScalar - specify a particular data item
I have a Store开发者_开发技巧d Procedure which returns 10 columns of data. Using cmd.ExecuteScalar()
returns the value of the 1st column from the 1st record.
How can I change this so that I can return different columns, by specifying their alias/dataitem name?
I want to be able to do something like:
Dim FirstName as String = cmd.ExecuteScalar("FirstName")
You could create a method that calls ExecuteReader, and then uses GetOrdinal with your column name to then call GetString.
My VB is non-existent, but this is the C# for an extension method.
public static class SqlCommandExt
{
public static string ExecuteScalar(this SqlCommand cmd, string columnName)
{
using (var reader = cmd.ExecuteReader())
{
if (!reader.Read())
return null;
var index = reader.GetOrdinal(columnName);
return reader.GetString(index);
}
}
}
You can not. Command.ExecuteScalar
take no parameters ..
What you can do is to use a text command and modify its CommandText
property value to include the column you need to get:
command.CommandText = "SELECT " + columnName + " FROM Table WHERE Key = " + ...
You could create an extension method to do this for you. C# equiv (which I imagine you could translate to a VB.NET extension rather easily):
public static T ExecuteScalar<T>(this SqlCommand cmd, String columnName)
{
using(var reader = cmd.ExecuteReader())
{
var item = default(T);
if(reader.Read())
{
item = (T)dataReader.GetValue(dataReader.GetOrdinal(columnName))
}
return item;
}
}
... and invoke it like so:
var firstName = cmd.ExecuteScalar<String>("FirstName");
You should try the below code also.
Private Sub YourFunctionName()
Using con As System.Data.SqlClient.SqlConnection = New SqlConnection("YourConnection string")
con.Open()
Using cmd As SqlCommand = New SqlCommand
Dim expression As String = "Parameter value"
cmd.CommandType = CommandType.StoredProcedure
cmd.CommandText = "Your Stored Procedure"
cmd.Parameters.Add("Your Parameter Name", SqlDbType.VarChar).Value = expression
cmd.Connection = con
Using dr As IDataReader = cmd.ExecuteReader()
If dr.Read() Then
Dim str As String = dr("YourColumnName").ToString()
End If
End Using
End Using
End Using
End Sub
精彩评论