我有以下存储过程:
ALTER PROCEDURE [dbo].[ProcedureName]
@date NVARCHAR(50)
AS
BEGIN
SET NOCOUNT ON;
DECLARE @result nvarchar(500) -- this one should return string.
DECLARE @variable1 NVARCHAR(50)
set @variable1 = (SELECT COUNT(*) FROM dbo.Table1 WHERE column1 not in (select column1 from dbo.Table2))
DECLARE @variable2 NVARCHAR(50)
update dbo.Table1 set columnX = 1 where column1 not in (select column1 from dbo.Table2)
set @variable2 = @@ROWCOUNT
依此类推......它继续像200行至少有10-12个变量的脚本
之后我想得到像这样的结果
'Hello,' +
'Some Text here' +
@date +': ' +
'Explaining text for variable1- ' + @variable1 +
'Updated rows from variable2 - ' + @variable2 +
'some other select count - ' + @variable3 +
'some other update rowcount - '+ @variable4
......
直到现在我能用PRINT语句得到这个,但是不能把它变成我的C#代码中的变量:
public void Execute_Click(object sender, EventArgs e)
{
if (MessageBox.Show("Are you sure you want to execute the program?", "Confirm Start", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.No)
{
string connectionString = GetConnectionString(usernamePicker.Text, passwordPicker.Text);
using (SqlConnection connection = new SqlConnection(connectionString))
{
using (SqlCommand cmd = new SqlCommand("dbo.ProcedureName", connection))
{
connection.Open();
cmd.CommandText = "dbo.ProcedureName";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("@date", SqlDbType.VarChar).Value = dateTimePicker1.Text;
SqlParameter result = cmd.Parameters.Add("@result", SqlDbType.VarChar);
result.Direction = ParameterDirection.ReturnValue;
cmd.ExecuteScalar();
var resultout = (string)cmd.Parameters["@result"].Value;
connection.Close();
TextMessage.Text = dateTimePicker1.Text;
}
}
}
}
我得到的结果是0或NULL等等。 我试图通过PRINT,RETURN,SET,OUTPUT .......从SQL返回值,但似乎没有任何效果。然而,从C#获取变量到SQL看起来像是儿童工作。有什么想法吗?
答案 0 :(得分:4)
如果要将连接字符串作为输出返回,则在过程结束时只需编写select @result
。确保在此声明之前已将其连接起来。
这将返回您可以在c#代码中用作字符串的字符串。
答案 1 :(得分:0)
将存储过程更改为:
ALTER PROCEDURE [dbo].[ProcedureName]
@date NVARCHAR(50),
@variable1 NVARCHAR(50) output,
@variable2 NVARCHAR(50) output
AS
BEGIN
SET NOCOUNT ON;
DECLARE @result nvarchar(500) -- this one should return string.
set @variable1 = (SELECT COUNT(*) FROM dbo.Table1 WHERE column1 not in (select column1 from dbo.Table2))
update dbo.Table1 set columnX = 1 where column1 not in (select column1 from dbo.Table2)
set @variable2 = @@ROWCOUNT
并修改你的代码:
SqlParameter result1 = cmd.Parameters.Add("@variable1", SqlDbType.VarChar);
result1.Direction = ParameterDirection.ReturnValue;
SqlParameter result2 = cmd.Parameters.Add("@variable2", SqlDbType.VarChar);
result2.Direction = ParameterDirection.ReturnValue;
答案 2 :(得分:0)
好吧,我可以说我做了这个程序
ALTER PROCEDURE [dbo].[ProcedureName]
@date NVARCHAR(50),
@result nvarchar(500) output
AS
BEGIN
SET NOCOUNT ON;
DECLARE @variable1 NVARCHAR(50)
set @variable1 = (SELECT COUNT(*) FROM dbo.Table1 WHERE column1 not in (select column1 from Table2))
set @result = @variable1 + ' some text '
我希望“@result”从过程输出文本并使用C#
获取