我想在数据库中插入一个记录,然后需要返回一行
本文关键字:然后 返回 一行 记录 一个 插入 数据库 | 更新日期: 2023-09-27 18:10:38
我想在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]
一种方法是将@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;
}
}
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 !!");
更多信息在这里