我正在尝试从存储过程中获取插入或更新的 id,我尝试了 2 种不同的方法
If exists(select ....)
出于性能原因,我不允许使用
1-使用输出
@firstName varchar(30),
@Telephone int
AS
BEGIN transaction
UPDATE [PHONE_BOOK].[dbo].[USER]
SET TELEPHONE= @Telephone
output inserted.USERID
where FIRST_NAME = @firstName
if @@ROWCOUNT = 0
begin
INSERT INTO [PHONE_BOOK].[dbo].[USER]
([FIRST_NAME]
,[TELEPHONE])
output inserted.USERID -- or output SCOPE_IDENTITY()
VALUES
(@firstName
,@Telephone)
end
C# 代码
IList<SqlParameter> parameters = new List<SqlParameter>();
parameters.Add(new SqlParameter("@firstName", "Mike"));
parameters.Add(new SqlParameter("@Telephone", 9514256));
using (var sqlConnection = new SqlConnection(Config.ConnString))
{
sqlConnection.Open();
using (SqlCommand command = sqlConnection.CreateCommand())
{
command.CommandType = CommandType.StoredProcedure;
command.CommandText = "[dbo].[INSET_USER]";
command.UpdatedRowSource = UpdateRowSource.None;
foreach (SqlParameter oPar in parameters)
command.Parameters.Add(oPar);
object x = command.ExecuteScalar();
}
}
- 如果更新 ==>
x
是正确的 - 如果删除 ==>
x
为空
2- 使用 OUTPUT 参数
@firstName varchar(30),
@Telephone int,
@userId int output
AS
BEGIN transaction
UPDATE [PHONE_BOOK].[dbo].[USER]
SET TELEPHONE= @Telephone
where FIRST_NAME = @firstName
-- i can't find different way to set @userId than doing a select which is not acceptable
if @@ROWCOUNT = 0
begin
INSERT INTO [PHONE_BOOK].[dbo].[USER]
([FIRST_NAME]
,[TELEPHONE])
VALUES
(@firstName
,@Telephone)
set @userId = SCOPE_IDENTITY()
end
c#代码:
IList<SqlParameter> parameters = new List<SqlParameter>();
parameters.Add(new SqlParameter("@firstName", "Mike"));
parameters.Add(new SqlParameter("@Telephone", 9514256));
using (var sqlConnection = new SqlConnection(Config.ConnString))
{
sqlConnection.Open();
using (SqlCommand command = sqlConnection.CreateCommand())
{
command.CommandType = CommandType.StoredProcedure;
command.CommandText = "[dbo].[INSET_USER]";
command.UpdatedRowSource = UpdateRowSource.None;
foreach (SqlParameter oPar in parameters)
command.Parameters.Add(oPar);
command.Parameters.Add("@userId",0).Direction = ParameterDirection.Output;
command.ExecuteNonQuery();
var x = command.Parameters["@userId"].Value;
}
}
- 如果更新 ==>
x
为 -1 - 如果删除 ==>
x
是正确的
我怎样才能解决这个问题?我喜欢第一个选项,因为我不需要将输出参数传递给存储过程