SQL Server 2008 R2 Insert Stored Procedure Syntax with Identity Field
Good Afternoon,
I've written a very basic stored procedure that will be used to insert QuestionText and QuestionStatus into the Questions table with QuestionID int Primary Key set as having Identity.
The syntax is as follows:
CREATE PROCEDURE InsertNewQuestion
-- Add the parameters for the stored proce开发者_如何转开发dure here
@QuestionText varchar(200), @QuestionStatus bit
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
-- Insert statements for procedure here
INSERT into Questions
(QuestionText,QuestionStatus)
Values
(@QuestionText),(@QuestionStatus)
END
GO
When I execute the stored procedure, I receive the following error:
There are more columns in the INSERT statement than values specified in the VALUES clause. The number of values in the VALUES clause must match the number of columns specified in the INSERT statement.
What is the correct syntax to use to properly insert a record and allow for QuestionID to auto-increment upon each insertion?
Thanks much for your help and guidance.
Updated Stored Procedure Syntax
Remove QuestionID and @@Identity + Values should be (@QuestionText,@QuestionStatus)
INSERT into Questions
(QuestionText,QuestionStatus)
Values
(@QuestionText,@QuestionStatus)
SQL Server knows that QuestionID is an Identity field and will increment it.... :-)
If you need to return the Identity that was inserted then create an out parameter on the SP and get it by calling SCOPE_IDENTITY().
SET @QuestionID = SCOPE_IDENTITY()
You do not specify the identity columns, and the values are not supposed to be in their own parenthesis.
INSERT into Questions
(QuestionText,QuestionStatus)
Values
(@QuestionText, @QuestionStatus)
INSERT into Questions (QuestionText,QuestionStatus)
Values (@QuestionText,@QuestionStatus)
i.e. without the identity field specified.
CREATE PROCEDURE SPWITHPARAMETER_AND_RETURN_VALUE
(
@EMPID INT,
@IDVAL INT,
@RETURNVALUE INT =0 OUT
)
AS
DECLARE @COUNT INT
BEGIN
SELECT @COUNT=COUNT(*) FROM JOINTABLE WHERE EMPID=@EMPID AND IDVAL=@IDVAL
IF(@COUNT >0)
BEGIN
SET @RETURNVALUE = 1;
PRINT @RETURNVALUE
RETURN @RETURNVALUE
END
ELSE
BEGIN
SET @RETURNVALUE = 1;
PRINT @RETURNVALUE
RETURN @RETURNVALUE
END
END
精彩评论