SQL Server错误。只有在使用列列表且IDENTITY_INSERT为ON时才能指定Identity Column ....的显式值

时间:2013-06-10 08:53:44

标签: sql-server sql-server-2008 stored-procedures

我正在尝试创建过程,这会产生一个错误陈述

只有在使用列列表和tblRegisterUser时才能指定表IDENTITY_INSERT is ON中标识列的显式值。

我试图用INDENTITY_INSERT to ON包围插入语句,但这也不起作用。我错过了什么,或者我包含的子查询是错误的吗?

以下是存储过程

CREATE PROCEDURE dbo.spInsertUserRegister
(
    @FirstName nvarchar(50),
    @LastName nvarchar(50),
    @Username nvarchar(50),
    @Password nvarchar(50),
    @Designation nvarchar(50),
    @Department nvarchar(50),
    @IsAdmin bit
)
AS
BEGIN
    INSERT INTO tblRegisterUser Values
    (
        @FirstName, @LastName, @Username, @Password,@Designation,@Department,@IsAdmin
    )
    DECLARE @UID INT
    SET @UID = @@IDENTITY
    INSERT INTO tblLogin(Username,Password,UID,IsAdmin) 
    Values(@Username, @Password, @UID,(SELECT IsAdmin FROM tblRegisterUser WHERE     Username=@Username AND Password=@Password))
END

2 个答案:

答案 0 :(得分:2)

如果tblRegisterUser表的结构类似于

ID int primary_key autoincrement
FirstName varchar
LastName varchar 
Username varchar
Password varchar
Designation varchar
Department varchar
IsAdmin bit

比这句话错了:

INSERT INTO tblRegisterUser Values
(
    @FirstName, @LastName, @Username, @Password, 
    @Designation,@Department,@IsAdmin
)

您应该使用显式列列表来指定列:

INSERT INTO tblRegisterUser 
(  FirstName, LastName, Username, Password,
   Designation, Department, IsAdmin) 
VALUES 
(
    @FirstName, @LastName, @Username, @Password, 
    @Designation,@Department,@IsAdmin
)

这样就会自动填充ID字段,@@Identity语句应该正确返回。


也就是说,SQL Server has a few functions返回最后一行的生成ID,每个行都有自己特定的优点和缺点。

基本上:

    如果您不使用触发器
  • @@IDENTITY,则可以使用
  • SCOPE_IDENTITY()适用于您明确调用的代码。
  • IDENT_CURRENT(‘tablename’)适用于所有范围内的特定表格。

在几乎所有情况下SCOPE_IDENTITY()都是您需要的,使用它是一个好习惯,与其他选项相反。
还可以对这些方法的利弊进行讨论here

this answer

复制

答案 1 :(得分:1)

试试这个 -

CREATE PROCEDURE dbo.spInsertUserRegister 
(
    @FirstName NVARCHAR(50),
    @LastName NVARCHAR(50),
    @Username NVARCHAR(50),
    @Password NVARCHAR(50),
    @Designation NVARCHAR(50),
    @Department NVARCHAR(50),
    @IsAdmin BIT
)
AS BEGIN

    INSERT INTO dbo.tblRegisterUser (FirstName, LastName, Username, [Password], Designation, Department, IsAdmin)
    SELECT @FirstName, @LastName, @Username, @Password, @Designation, @Department, @IsAdmin

    DECLARE @ID BIGINT
    SELECT @ID = SCOPE_IDENTITY()

    --SET IDENTITY_INSERT dbo.tblLogin ON;

    INSERT INTO dbo.tblLogin (UserName, [password], [uid], IsAdmin)
    SELECT @Username, @Password, @ID, IsAdmin 
    FROM tblRegisterUser 
    WHERE UserName = @Username 
        AND [password] = @Password

    --SET IDENTITY_INSERT dbo.tblLogin OFF;

END