-5

我想在数据库中插入一条记录,然后需要返回一行。我创建了查询,但如何在 .cs 中使用它(C# 代码)

这是我的查询

 @ledgerId numeric(18,0) ,
 @voucherNo varchar(MAX) ,
 @invoiceNo varchar(MAX) ,
 @date datetime ,
 @month datetime ,
 @totalAmount decimal(18,5) ,
 @narration varchar(MAX) ,
-- @extraDate datetime ,
 @extra1 varchar(MAX) ,
 @extra2 varchar(MAX) ,
 @suffixPrefixId numeric(18,0) ,
 @voucherTypeId numeric(18,0) 
AS
DECLARE @UpdatedVoucherNo DECIMAL(18,0)

SET @UpdatedVoucherNo = (SELECT ISNULL( MAX(CAST (voucherNo AS NUMERIC(18,0))),0) + 1
 FROM tbl_SalaryVoucherMaster
 WHERE voucherTypeId=@voucherTypeId)

 IF (@UpdatedVoucherNo = @voucherNo )

 INSERT INTO tbl_SalaryVoucherMaster
 (
            /*salaryVoucherMasterId,*/
            ledgerId,
            voucherNo,
            invoiceNo,
            date,
            month,
            totalAmount,
            narration,
            extraDate,
            extra1,
            extra2,
            suffixPrefixId,
            voucherTypeId )
VALUES
 (
            /*@salaryVoucherMasterId, */
            @ledgerId, 
            @voucherNo, 
            @invoiceNo, 
            @date, 
            @month, 
            @totalAmount, 
            @narration, 
            getDate(), 
            @extra1, 
            @extra2,
            @suffixPrefixId,
            @voucherTypeId)

            SELECT SCOPE_IDENTITY() AS [Identity],0 AS [UpdatedVoucherNo]
4

2 回答 2

0

一种方法是修改@voucherNo为一个OUTPUT参数,然后在查询中添加一个新OUTPUT参数以返回SCOPE_IDENTITY().

@voucherNo varchar(max)
@ScopeIdentity numeric(38,0)

并修改最后一条SELECT语句以设置 @ScopeIdentity 参数的值。

SELECT @ScopeIdentity = SCOPE_IDENTITY()

然后用于SqlCommand.ExecuteNonQuery执行查询,并在完成时从输出参数中读取值。

using (SqlCommand command = new SqlCommand(connection, commandText))
{
    int rowsAffected = command.ExecuteNonQuery();
    if (rowsAffected > 0)
    {
        var voucherNo = (string)command.Parameters["@voucherNo].Value;
        var identity = (decimal)command.Parameters["@ScopeIdentity"].Value;
    }
}
于 2013-05-14T20:17:48.397 回答
0

Command.ExecuteNonQuery();是您所需要的,它返回int插入和更新数据时受影响的行数(),

这是一个使用它的例子,

            string connetionString = null;
            SqlConnection cnn ;
            SqlCommand cmd ;
            string sql = null;

            connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password";
            sql = "Your SQL Statemnt Here";

            cnn = new SqlConnection(connetionString);

                cnn.Open();
                cmd = new SqlCommand(sql, cnn);
                int rowsAffected = cmd.ExecuteNonQuery();
                if (rowsAffected > 0)
                {
                    //do anything
                }
                cmd.Dispose();
                cnn.Close();
                MessageBox.Show (" ExecuteNonQuery in SqlCommand executed !!");

更多信息在这里

于 2013-04-23T03:51:58.183 回答