从存储过程获取结果,然后传递给WPF TextBox

时间:2018-03-23 07:00:06

标签: sql wpf

我有这个执行正常的存储过程:

ALTER PROCEDURE [dbo].[SP_GENERATETICKET] 
@RESULT AS VARCHAR(255) OUTPUT
AS
BEGIN
DECLARE @D AS DATETIME = GETDATE()
DECLARE @LASTTICKET AS VARCHAR(50) ;
DECLARE @NUM AS VARCHAR(50);
SET @LASTTICKET=(SELECT TOP 1 TICKETNO FROM tblTicket WHERE 
MONTH(ENTRYVEHICLE  ) = MONTH(@D ) ORDER BY TICKETNO DESC);
IF (CONVERT(VARCHAR(10),YEAR(@D),110) <> CONVERT(VARCHAR(10),YEAR(GETDATE()),110))--IF YEAR IS DIFFERENT, RESET SERIES
    BEGIN
        SET @NUM = '1'
    END
ELSE
    BEGIN 
        IF ISNULL(@LASTTICKET,'1')  = '1'--IF MONTH IS DIFFERENT, RESET SERIES
            BEGIN
                SET @NUM ='1'
            END
        ELSE
        BEGIN
                SET @NUM = CAST(CAST (RIGHT(@LASTTICKET,5) AS INT) + 1 AS VARCHAR)
        END
    END

SET @RESULT = RIGHT(CONVERT(VARCHAR(10),@D,101),2) + '-' + LEFT(CONVERT(VARCHAR(10),@D,101),2) + '-' + RIGHT('0000'+CAST(@NUM AS VARCHAR),5)
SELECT @RESULT
END

我有这个代码,但它返回null

SqlConnection con = new SqlConnection(gsql.connectionString);
SqlCommand command = new SqlCommand("SP_GENERATETICKET", con);

try
{
    con.Open();
    command.CommandType = CommandType.StoredProcedure;

    SqlParameter result = command.Parameters.Add("@RESULT", SqlDbType.VarChar);
    result.Direction = ParameterDirection.Output;

    txtTicket.Text = (string)command.Parameters["@RESULT"].Value;
}
    catch(Exception ex)
{
    MessageBox.Show(ex.Message);
}

我该怎么办?

2 个答案:

答案 0 :(得分:1)

那里有问题,你忘了执行命令

command.ExecuteNonQuery()

没有执行命令,你想要得到结果。

你也忘记为你的varchar参数添加大小,所以添加东西行

result.Size = 8000;

以下代码

您的代码将是,您需要使用using为您处理事情

using(SqlConnection con = new SqlConnection(gsql.connectionString))
{
    using(SqlCommand command = new SqlCommand("SP_GENERATETICKET", con))
    {
        try
        {
            con.Open();
            command.CommandType = CommandType.StoredProcedure;

            SqlParameter result = command.Parameters.Add("@RESULT", SqlDbType.VarChar);
            result.Size = 8000;//add parameter size 
            result.Direction = ParameterDirection.Output;
            command.ExecuteNonQuery();//this line need to be added 
            txtTicket.Text = (string)command.Parameters["@RESULT"].Value;
        }
        catch(Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }
}

答案 1 :(得分:0)

参数是一种很好的做法,但对于输出,你不能使用SQL注入(我知道)。

con.Open();
command.CommandType = CommandType.StoredProcedure;  
txtTicket.Text = (string)command.ExecuteScalar();

对于尺寸,您可以使用以下语法:

SqlParameter result = command.Parameters.Add("@RESULT", SqlDbType.VarChar, 800);