我意识到这个问题以前已经回答过了,我已经浏览了答案,试图找出我的方式的错误,但我处于停滞状态。我有以下应该返回唯一键的存储过程。
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
ALTER PROCEDURE [dbo].[newid] @tablename AS CHAR(10), @fieldname AS CHAR(15) = '', @ioffset AS INT, @theID as int = 0 output
AS
BEGIN
SET NOCOUNT ON
DECLARE @value AS INT
IF @ioffset < 1 SET @ioffset = 1
IF LEN(@fieldname) > 0
BEGIN
UPDATE id SET @value = CONVERT(INT,cvalue)+@ioffset-1, cvalue = CONVERT(CHAR,(CONVERT(INT,cvalue)+@ioffset)) WHERE UPPER(ctablename) = UPPER(@tablename) AND UPPER(cfieldname) = UPPER(@fieldname)
SELECT @value
END
ELSE
BEGIN
UPDATE id SET @value = CONVERT(INT,cvalue)+@ioffset-1, cvalue = CONVERT(CHAR,(CONVERT(INT,cvalue)+@ioffset)) WHERE UPPER(ctablename) = UPPER(@tablename)
SELECT @value
End
SET NOCOUNT OFF
set @theID = @value
END
我正在使用以下代码尝试访问该过程:
using(SqlConnection connection = new SqlConnection(connectionString))
using(SqlCommand command = new SqlCommand("dbo.NewID", connection)
{ CommandType = CommandType.StoredProcedure } )
{
command.Parameters.Add( new SqlParameter("@tablename",table));
command.Parameters.Add( new SqlParameter("@fieldname",field));
command.Parameters.Add( new SqlParameter("@ioffset",1));
SqlParameter key = new SqlParameter("@theID", SqlDbType.Int);
key.Direction = ParameterDirection.Output;
command.Parameters.Add(key);
connection.Open();
result = command.ExecuteNonQuery();
connection.Close();
}
key.Value 返回为空,结果为 -1,暗示运行该过程时出错。如果有人看到我可能做错了什么,我将非常感谢您的帮助。
请注意:我无法编辑实际过程,因为有几个类已经使用它。
非常感谢您的任何帮助。