我的服务器上有一个存储过程,它插入一些参数并返回插入的ID
。我正在写一个表单来轻松完成这个,但我似乎无法获得传回的参数。
为了节省你做一大堆可能毫无意义的阅读,最好只关注我的C#代码并让我知道我需要做什么才能传递参数并得到一个回报。
C#Default.aspx
connection = new SqlConnection(ConfigurationManager.AppSettings["ConnectionInfo"]);
sql = "aStoredProc";
command = new SqlCommand(sql, connection);
command.CommandType = CommandType.StoredProcedure;
command.Parameter.Add(new SqlParameter("@FirstName", SqlDbType.VarChar)).Value = sFirstname;
command.Parameter.Add(new SqlParameter("@SurName", SqlDbType.VarChar)).Value = sSurname;
connection.Open();
int ID = command.ExecuteNonQuery();
connection.Close();
SQL aStoredProc
IF EXISTS(SELECT * FROM aTable WHERE ID = @ID)
-- User exists, update details
BEGIN
BEGIN TRAN
UPDATE aTable
SET
FirstName = @FirstName,
SurName = @SurName,
LastUpdate = GetDate()
WHERE ID = @ID
IF (@@Error != 0)
ROLLBACK TRAN
ELSE
COMMIT TRAN
END
ELSE
-- New user
BEGIN
BEGIN TRAN
INSERT aTable (
FirstName,
SurName,
GetDate()
)
VALUES (
@FirstName,
@SurName,
@LastUpdate
)
SELECT @ID = @@IDENTITY
IF (@@Error != 0)
ROLLBACK TRAN
ELSE
COMMIT TRAN
END
参数@ID
在存储过程中列为:
@ID (int, Input/Output, No default)
和proc有'返回整数'。在SQL Server 2005升级之前,这曾经适用于VBA解决方案。
提前致谢。
答案 0 :(得分:6)
connection = new SqlConnection(ConfigurationManager.AppSettings["ConnectionInfo"]);
sql = "aStoredProc";
command = new SqlCommand(sql, connection);
command.CommandType = CommandType.StoredProcedure;
command.Parameter.Add(new SqlParameter("@FirstName", SqlDbType.VarChar)).Value = sFirstname;
command.Parameter.Add(new SqlParameter("@SurName", SqlDbType.VarChar)).Value = sSurname;
command.Parameter.Add(new SqlParameter("@SurName", SqlDbType.VarChar)).Value = sSurname;
SqlParameter ParamId = cmd.Parameters.Add( "@Id", SqlDbType.Int);
command.Direction = ParameterDirection.InputOutput;
command.Parameter.Add(ParamId);
connection.Open();
command.ExecuteNonQuery();
int ID = ParamId.Value;
connection.Close();
答案 1 :(得分:2)
您的SQL中有错误,它应该如下所示:
INSERT aTable (FirstName,SurName,LastUpdate)
VALUES (@FirstName, @SurName, GetDate() )
不喜欢这样:
INSERT aTable (
FirstName,
SurName,
GetDate()
)
VALUES (
@FirstName,
@SurName,
@LastUpdate
)