我想在DB中插入一条记录,然后需要返回一行。我创建了查询但是如何在.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]
答案 0 :(得分: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 !!");
更多信息here
答案 1 :(得分: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;
}
}