sql-server – 如何使用除标识列之外的每一列复制行(SQL Server 2005)

前端之家收集整理的这篇文章主要介绍了sql-server – 如何使用除标识列之外的每一列复制行(SQL Server 2005)前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我的代码
SELECT * INTO #t FROM CTABLE WHERE CID = @cid   --get data,put into a temp table


ALTER TABLE #t
DROP COLUMN CID       -- remove primary key column CID


INSERT INTO CTABLE SELECT * FROM #t   -- insert record to table
DROP TABLE #t                                -- drop temp table

错误是:

Msg 8101,An explicit value for the identity column in table 'CTABLE' can only 
be specified when a column list is used and IDENTITY_INSERT is ON.

而我确实设定了

SET IDENTITY_INSERT CTABLE OFF
GO

解决方法

DECLARE 
    @cid INT,@o   INT,@t   NVARCHAR(255),@c   NVARCHAR(MAX),@sql NVARCHAR(MAX);

SELECT
    @cid = 10,@t   = N'dbo.CTABLE',@o   = OBJECT_ID(@t);

SELECT @c = COALESCE(@c,'') + ',' + QUOTENAME(name)
    FROM sys.columns
    WHERE [object_id] = @o
    AND is_identity = 0;

SELECT @c = STUFF(@c,1,'');

SET @sql = 'SELECT ' + @c + ' INTO #t 
    FROM ' + @t + ' WHERE CID = ' + RTRIM(@cid) + ';

    INSERT ' + @t + '('+ @c + ') 
    SELECT ' + @c + ' FROM #t;' 

PRINT @sql;
-- exec sp_executesql @sql;

但是,构建以下sql并完全避免#temp表似乎要容易得多:

SET @sql = 'INSERT ' + @t + '(' + @c + ') 
    SELECT ' + @c + ' FROM ' + @t + '
    WHERE CID = ' + RTRIM(@cid);

PRINT @sql;
-- exec sp_executesql @sql;
原文链接:https://www.f2er.com/mssql/78890.html

猜你在找的MsSQL相关文章