使用SCOPE_IDENTITY()未获取新创建的行的ID

时间:2014-01-23 13:52:35

标签: sql-server-2008 stored-procedures

我有一个存储过程,我在其中创建一个字符串中的insert语句,然后执行该语句。 当我使用SCOPE_IDENTITY()来检索新插入记录的id时,它返回NULL。

请检查以下代码 -

ALTER PROCEDURE [dbo].[sgi_sp_SaveCompComponent] 
    -- Add the parameters for the stored procedure here
    @Id int output, 
    @ComponentName nvarchar(50), 
    @VehicleSystemId nvarchar(10), 
    @NamingConvension nvarchar(50), 
    @IsSubcomponent bit=0, 
    @SubComponentId int=null,
    @CompanyID  int = 0
AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;

    -- Insert statements for procedure here
    Declare @TableName nvarchar(100) ='C'+ cast(@CompanyID as nvarchar(10)) +'_Components',
    @AssociatedTable nvarchar(100)='C'+cast(@CompanyID as nvarchar(10))+'_'+ +REPLACE(@ComponentName,' ','');
    DECLARE @cmd AS NVARCHAR(max)
    -- Insert statements for procedure here
    Set @cmd='insert into '+@TableName+ '( ComponentName, VehicleSystemId, NamingConvension, IsSubcomponent, SubComponentId, AssociatedTable) values(''';
    set @cmd = @cmd + @ComponentName+''','''+ @VehicleSystemId+''','''+@NamingConvension+ ''','''+cast(@IsSubcomponent as nvarchar(10));
    if (@SubComponentId is null)
        set @cmd = @cmd +''',NULL,'''+@AssociatedTable +''')';
    else    
        set @cmd = @cmd +''','''+cast(@SubComponentId as nvarchar(10))+''','''+@AssociatedTable +''');';

    print (@cmd)
    exec (@cmd)
    set @Id=SCOPE_IDENTITY();
    print (@Id)
END

任何人都可以帮我解决这个问题

感谢您分享宝贵的时间。

0 个答案:

没有答案