我在SQL Server中有一个存储过程,它返回两个值。使用以下SQL代码从QA调用时:
exec TWEEPush_ValidateCO @CoFilter='CO IN(''1502'',''Mike'',''Clarkson'')', @TDate='09/18/`2017'
它通过返回两个值按预期工作:
@TempCOID @TempDate
1502 09/10/2017
存储过程执行一些操作,并以两个值设置为非空值结束,存储过程以:
结尾SELECT
@TempCOID AS N'@TempCOID',
@TempDate AS N'@TempDate'
在VB.net(Visual Basic,而不是C)中,我尝试了许多不同的方法来获得结果,但没有运气。我得到一个错误,说命名的param不存在,或者它最终返回空值(所有内容都被编码以防止返回数据中的Null)
Dim sConnectStr As String = GetSQLConnectionString()
Try
Using Connection As New SqlConnection(sConnectStr)
Connection.Open()
Dim Command As New SqlCommand("dbo.TWEEPush_ValidateCO", Connection)
Command.CommandType = CommandType.StoredProcedure
Command.Parameters.AddWithValue("@CoFilter", Filter)
Command.Parameters.AddWithValue("@TDate", Now())
Dim PramCOIDRet As New SqlParameter
PramCOIDRet.ParameterName = "@TempCOID"
PramCOIDRet.SqlDbType = SqlDbType.NVarChar
PramCOIDRet.Size = 30
PramCOIDRet.Direction = ParameterDirection.Output
Dim PramDateRet As New SqlParameter
PramDateRet.ParameterName = "@TempDate"
PramDateRet.SqlDbType = SqlDbType.NVarChar
PramDateRet.Size = 30
PramDateRet.Direction = ParameterDirection.Output
Command.Parameters.Add(PramCOIDRet)
Command.Parameters.Add(PramDateRet)
Command.ExecuteNonQuery()
Dim COID as string = Command.Parameters("@TempCOID").Value
Dim CoDate as Date = CDate(Command.Parameters("@TempDate").Value)
End Using
Catch ex As Exception
End Try
无论我尝试过什么代码,代码都不会按预期返回数据。 我究竟做错了什么?有人可以请一点解决这个问题吗?
答案 0 :(得分:2)
您没有向我们展示您的存储过程代码 - 但最有可能的是,它是这样的:
CREATE PROCEDURE dbo.dbo.TWEEPush_ValidateCO
@CoFilter VARCHAR(100), -- just guessing here!
@TDate DATE -- again - just guessing
AS
BEGIN
DECLARE @TempCOID INT;
DECLARE @TempDate DATE;
-- do some calculations here that define @TempCOID and @TempDate
-- this is just for demo purposes - I'm sure your calculation is a bit
-- more complex and involved...
SET @TempCOID = 1502;
SET @TempDate = '20170910';
-- return the values in a SELECT statement
SELECT
@TempCOID AS N'@TempCOID',
@TempDate AS N'@TempDate'
END
在这种情况下,你返回结果集 - 而不是两个参数!
你需要得到这样的价值观:
static void Main(string[] args)
{
string connectionString = ConfigurationManager.ConnectionStrings["YourConnectionString"].ConnectionString;
int tempCoid;
DateTime tempDate;
using (SqlConnection conn = new SqlConnection(connectionString))
using (SqlCommand cmd = new SqlCommand("dbo.dbo.TWEEPush_ValidateCO", conn))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@CoFilter", Filter);
cmd.Parameters.AddWithValue("@TDate", DateTime.Now);
conn.Open();
using (var rdr = cmd.ExecuteReader())
{
while (rdr.Read())
{
tempCoid = rdr.GetFieldValue<int>(0);
tempDate = rdr.GetFieldValue<DateTime>(1);
}
}
conn.Close();
}
}
(我相信你明白了 - 你也可以很容易地把它翻译成VB.NET。)
希望有所帮助!
马克