我正在尝试在Visual Studio中执行存储过程。它在下面给出。
CREATE PROCEDURE [dbo].[addStudent] @stuName varchar(50), @address varchar(100), @tel varchar(15), @etel varchar(15), @nic varchar (10), @dob date AS BEGIN SET NOCOUNT ON; DECLARE @currentID INT DECLARE @existPerson INT SET @existPerson = (SELECT p_ID FROM Student WHERE s_NIC = @nic); IF @existPerson = null BEGIN INSERT INTO Person (p_Name, p_RegDate, p_Address, p_Tel, p_EmergeNo, p_Valid, p_Userlevel) VALUES (@stuName, GETDATE(), @address, @tel, @etel, 0, 'Student' ); SET @currentID = (SELECT MAX( p_ID) FROM Person); INSERT INTO Student (p_ID, s_Barcode, s_DOB, s_NIC) VALUES (@currentID , NULL, @dob, @nic); return 0; END ELSE return -1; END
我通过使用下面的代码来做到这一点。
SqlConnection con = new SqlConnection(); Connect conn = new Connect(); con = conn.getConnected(); con.Open(); cmd = new SqlCommand("addStudent", con); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.Add("@stuName", SqlDbType.VarChar).Value = nameTxt.Text.ToString(); cmd.Parameters.Add("@address", SqlDbType.VarChar).Value = addressTxt.Text.ToString(); cmd.Parameters.Add("@tel", SqlDbType.VarChar).Value = telTxt.Text.ToString(); cmd.Parameters.Add("@etel", SqlDbType.VarChar).Value = emerTxt.Text.ToString(); cmd.Parameters.Add("@nic", SqlDbType.VarChar).Value = nicTxt.Text.ToString(); cmd.Parameters.Add("@dob", SqlDbType.DateTime).Value = dobTime.Value.ToString("MM-dd-yyyy"); int n = cmd.ExecuteNonQuery(); MessageBox.Show(n.ToString());
但是它返回我-1。我输入了从调试中捕获的相同值来尝试了此存储过程。成功了。可能是什么错误?非常感谢!
不要使用= null,使用is null
= null
is null
IF @existPerson is null
当您比较任何内容时= null,结果始终为假(除非您拥有set ansi_nulls off,否则不应该这样做,因为不赞成使用此选项)
set ansi_nulls off
更好的是,您可以使用
IF NOT EXISTS (SELECT p_ID FROM Student WHERE s_NIC = @nic)
另外,您应该使用SCOPE_IDENTITY()而不是SET @currentID = (SELECT MAX( p_ID) FROM Person);
SCOPE_IDENTITY()
SET @currentID = (SELECT MAX( p_ID) FROM Person);
SET @currentID = SCOPE_IDENTITY()
最后,您还需要添加一个参数来收集返回值
SqlParameter retValue = cmd.Parameters.Add("return", SqlDbType.Int); retValue.Direction = ParameterDirection.ReturnValue;
然后
MessageBox.Show(retValue.Value);