我希望能够将带有标识列的表中的数据插入到SQL Server 2005中的临时表中。
TSQL类似于:
-- Create empty temp table
SELECT *
INTO #Tmp_MyTable
FROM MyTable
WHERE 1=0
...
WHILE ...
BEGIN
...
INSERT INTO #Tmp_MyTable
SELECT TOP (@n) *
FROM MyTable
...
END
上面的代码使用标识列创建了#Tmp_Table,然后插入失败并显示错误“只有在使用列列表且IDENTITY_INSERT为ON时,才能指定表'#Tmp_MyTable'中标识列的显式值。“
TSQL中有没有办法在临时表中删除列的标识属性而不明确列出所有列?我特别想使用“SELECT *”,这样如果将新列添加到MyTable,代码将继续有效。
我相信删除并重新创建列会改变它的位置,因此无法使用SELECT *。
更新
我尝试在一个响应中建议使用IDENTITY_INSERT。它不起作用 - 见下面的repro。我做错了什么?
-- Create test table
CREATE TABLE [dbo].[TestTable](
[ID] [numeric](18, 0) IDENTITY(1,1) NOT NULL,
[Name] [varchar](50) NULL,
CONSTRAINT [PK_TestTable] PRIMARY KEY CLUSTERED
(
[ID] ASC
)
)
GO
-- Insert some data
INSERT INTO TestTable
(Name)
SELECT 'One'
UNION ALL
SELECT 'Two'
UNION ALL
SELECT 'Three'
GO
-- Create empty temp table
SELECT *
INTO #Tmp
FROM TestTable
WHERE 1=0
SET IDENTITY_INSERT #Tmp ON -- I also tried OFF / ON
INSERT INTO #Tmp
SELECT TOP 1 * FROM TestTable
SET IDENTITY_INSERT #Tmp OFF
GO
-- Drop test table
DROP TABLE [dbo].[TestTable]
GO
请注意,错误消息“表'#TmpMyTable'中标识列的显式值只能在使用列列表时指定且IDENTITY_INSERT为ON。” - 我特别不想使用如上所述的列列表。
更新2 试过the suggestion from Mike,但这也给出了同样的错误:
-- Create empty temp table
SELECT *
INTO #Tmp
FROM (SELECT
m1.*
FROM TestTable m1
LEFT OUTER JOIN TestTable m2 ON m1.ID=m2.ID
WHERE 1=0
) dt
INSERT INTO #Tmp
SELECT TOP 1 * FROM TestTable
至于为什么我要这样做:MyTable是一个临时表,可以包含大量要合并到另一个表中的行。我想处理登台表中的行,插入/更新我的主表,并在每个事务处理N行的循环中从登台表中删除它们。我意识到还有其他方法可以实现这一目标。
更新3
我无法使Mike's solution工作,但它建议使用以下解决方案:使用非标识列作为前缀并删除标识列:
SELECT CAST(1 AS NUMERIC(18,0)) AS ID2, *
INTO #Tmp
FROM TestTable
WHERE 1=0
ALTER TABLE #Tmp DROP COLUMN ID
INSERT INTO #Tmp
SELECT TOP 1 * FROM TestTable
迈克建议只在临时表中存储密钥也是一个很好的建议,但在这种特殊情况下,有理由我希望在临时表中包含所有列。
答案 0 :(得分:7)
你可以尝试
SET IDENTITY_INSERT #Tmp_MyTable ON
-- ... do stuff
SET IDENTITY_INSERT #Tmp_MyTable OFF
即使它有标识列,也可以选择#Tmp_MyTable
。
但不会工作:
-- Create empty temp table
SELECT *
INTO #Tmp_MyTable
FROM MyTable
WHERE 1=0
...
WHILE ...
BEGIN
...
SET IDENTITY_INSERT #Tmp_MyTable ON
INSERT INTO #Tmp_MyTable
SELECT TOP (@n) *
FROM MyTable
SET IDENTITY_INSERT #Tmp_MyTable OFF
...
END
(导致错误“只有在使用列列表并且IDENTITY_INSERT为ON时才能指定表'#Tmp'中标识列的显式值。”)
似乎没有办法实际删除列 - 但这会改变OP提到的列的顺序。丑陋的黑客:根据#Tmp_MyTable ...
创建一个新表我建议您编写一个存储过程,该存储过程基于具有相同列(按顺序)的表名(MyTable
)创建临时表,但缺少标识属性。
您可以使用以下代码:
select t.name as tablename, typ.name as typename, c.*
from sys.columns c inner join
sys.tables t on c.object_id = t.[object_id] inner join
sys.types typ on c.system_type_id = typ.system_type_id
order by t.name, c.column_id
了解反射在TSQL中的工作原理。我相信你必须循环遍历相关表的列并执行动态(手工制作,存储在字符串中然后评估)alter语句到生成的表。
你介意为世界其他地方发布这样的存储过程吗?这个问题在其他论坛中似乎也出现了很多......
答案 1 :(得分:3)
如果您只是按照描述处理行,那么将前N个主键值选择到临时表中会不会更好:
CREATE TABLE #KeysToProcess
(
TempID int not null primary key identity(1,1)
,YourKey1 int not null
,YourKey2 int not null
)
INSERT INTO #KeysToProcess (YourKey1,YourKey2)
SELECT TOP n YourKey1,YourKey2 FROM MyTable
密钥不应经常更改(我希望),但其他列可以这样做无害。
获取插入的@@ ROWCOUNT,你可以在TempID上轻松循环,从1到@@ ROWCOUNT
和/或
只需将#KeysToProcess加入您的MyKeys表即可,无需复制所有数据。
这在我的SQL Server 2005上运行正常,其中MyTable.MyKey是一个标识列。
-- Create empty temp table
SELECT *
INTO #TmpMikeMike
FROM (SELECT
m1.*
FROM MyTable m1
LEFT OUTER JOIN MyTable m2 ON m1.MyKey=m2.MyKey
WHERE 1=0
) dt
INSERT INTO #TmpMike
SELECT TOP 1 * FROM MyTable
SELECT * from #TmpMike
的修改
这个工作,没有错误......
-- Create empty temp table
SELECT *
INTO #Tmp_MyTable
FROM (SELECT
m1.*
FROM MyTable m1
LEFT OUTER JOIN MyTable m2 ON m1.KeyValue=m2.KeyValue
WHERE 1=0
) dt
...
WHILE ...
BEGIN
...
INSERT INTO #Tmp_MyTable
SELECT TOP (@n) *
FROM MyTable
...
END
但是,你真正的问题是什么?为什么在将“*”插入此临时表时需要循环?您可以改变策略并提出更好的算法。
答案 2 :(得分:1)
编辑按照Daren的建议切换IDENTITY_INSERT肯定是更优雅的方法,在我的情况下我需要删除标识列,以便我可以将所选数据重新插入到源表中
我解决这个问题的方法就是像你一样创建临时表,显式删除标识列,然后动态构建sql,以便我有一个排除标识列的列列表(如你的情况那样)如果模式有变化,proc仍然可以工作)然后在这里执行sql是一个样本
declare @ret int
Select * into #sometemp from sometable
Where
id = @SomeVariable
Alter Table #sometemp Drop column SomeIdentity
Select @SelectList = ''
Select @SelectList = @SelectList
+ Coalesce( '[' + Column_name + ']' + ', ' ,'')
from information_schema.columns
where table_name = 'sometable'
and Column_Name <> 'SomeIdentity'
Set @SelectList = 'Insert into sometable ('
+ Left(@SelectList, Len(@SelectList) -1) + ')'
Set @SelectList = @SelectList
+ ' Select * from #sometemp '
exec @ret = sp_executesql @selectlist
答案 3 :(得分:0)
我已经编写了这个程序,作为自动和快速删除列标识的许多答案的汇编:
CREATE PROCEDURE dbo.sp_drop_table_identity @tableName VARCHAR(256) AS
BEGIN
DECLARE @sql VARCHAR (4096);
DECLARE @sqlTableConstraints VARCHAR (4096);
DECLARE @tmpTableName VARCHAR(256) = @tableName + '_noident_temp';
BEGIN TRANSACTION
-- 1) Create temporary table with edentical structure except identity
-- Idea borrowed from https://stackoverflow.com/questions/21547/in-sql-server-how-do-i-generate-a-create-table-statement-for-a-given-table
-- modified to ommit Identity and honor all constraints, not primary key only!
SELECT
@sql = 'CREATE TABLE [' + so.name + '_noident_temp] (' + o.list + ')'
+ ' ' + j.list
FROM sysobjects so
CROSS APPLY (
SELECT
' [' + column_name + '] '
+ data_type
+ CASE data_type
WHEN 'sql_variant' THEN ''
WHEN 'text' THEN ''
WHEN 'ntext' THEN ''
WHEN 'xml' THEN ''
WHEN 'decimal' THEN '(' + CAST(numeric_precision as VARCHAR) + ', ' + CAST(numeric_scale as VARCHAR) + ')'
ELSE COALESCE('(' + CASE WHEN character_maximum_length = -1 THEN 'MAX' ELSE CAST(character_maximum_length as VARCHAR) END + ')', '')
END
+ ' '
/* + case when exists ( -- Identity skip
select id from syscolumns
where object_name(id)=so.name
and name=column_name
and columnproperty(id,name,'IsIdentity') = 1
) then
'IDENTITY(' +
cast(ident_seed(so.name) as varchar) + ',' +
cast(ident_incr(so.name) as varchar) + ')'
else ''
end + ' ' */
+ CASE WHEN IS_NULLABLE = 'No' THEN 'NOT ' ELSE '' END
+ 'NULL'
+ CASE WHEN information_schema.columns.column_default IS NOT NULL THEN ' DEFAULT ' + information_schema.columns.column_default ELSE '' END
+ ','
FROM
INFORMATION_SCHEMA.COLUMNS
WHERE table_name = so.name
ORDER BY ordinal_position
FOR XML PATH('')
) o (list)
CROSS APPLY(
SELECT
CHAR(10) + 'ALTER TABLE ' + @tableName + '_noident_temp ADD ' + LEFT(alt, LEN(alt)-1)
FROM(
SELECT
CHAR(10)
+ ' CONSTRAINT ' + tc.constraint_name + '_ni ' + tc.constraint_type + ' (' + LEFT(c.list, LEN(c.list)-1) + ')'
+ COALESCE(CHAR(10) + r.list, ', ')
FROM
information_schema.table_constraints tc
CROSS APPLY(
SELECT
'[' + kcu.column_name + '], '
FROM
information_schema.key_column_usage kcu
WHERE
kcu.constraint_name = tc.constraint_name
ORDER BY
kcu.ordinal_position
FOR XML PATH('')
) c (list)
OUTER APPLY(
-- https://stackoverflow.com/questions/3907879/sql-server-howto-get-foreign-key-reference-from-information-schema
SELECT
' REFERENCES [' + kcu1.constraint_schema + '].' + '[' + kcu2.table_name + ']' + '([' + kcu2.column_name + ']) '
+ CHAR(10)
+ ' ON DELETE ' + rc.delete_rule
+ CHAR(10)
+ ' ON UPDATE ' + rc.update_rule + ', '
FROM information_schema.referential_constraints as rc
JOIN information_schema.key_column_usage as kcu1 ON (kcu1.constraint_catalog = rc.constraint_catalog AND kcu1.constraint_schema = rc.constraint_schema AND kcu1.constraint_name = rc.constraint_name)
JOIN information_schema.key_column_usage as kcu2 ON (kcu2.constraint_catalog = rc.unique_constraint_catalog AND kcu2.constraint_schema = rc.unique_constraint_schema AND kcu2.constraint_name = rc.unique_constraint_name AND kcu2.ordinal_position = KCU1.ordinal_position)
WHERE
kcu1.constraint_catalog = tc.constraint_catalog AND kcu1.constraint_schema = tc.constraint_schema AND kcu1.constraint_name = tc.constraint_name
) r (list)
WHERE tc.table_name = @tableName
FOR XML PATH('')
) a (alt)
) j (list)
WHERE
xtype = 'U'
AND name NOT IN ('dtproperties')
AND so.name = @tableName
SELECT @sql as '1) @sql';
EXECUTE(@sql);
-- 2) Obtain current back references on our table from others to reenable it later
-- https://stackoverflow.com/questions/3907879/sql-server-howto-get-foreign-key-reference-from-information-schema
SELECT
@sqlTableConstraints = (
SELECT
'ALTER TABLE [' + kcu1.constraint_schema + '].' + '[' + kcu1.table_name + ']'
+ ' ADD CONSTRAINT ' + kcu1.constraint_name + '_ni FOREIGN KEY ([' + kcu1.column_name + '])'
+ CHAR(10)
+ ' REFERENCES [' + kcu2.table_schema + '].[' + kcu2.table_name + ']([' + kcu2.column_name + '])'
+ CHAR(10)
+ ' ON DELETE ' + rc.delete_rule
+ CHAR(10)
+ ' ON UPDATE ' + rc.update_rule + ' '
FROM information_schema.referential_constraints as rc
JOIN information_schema.key_column_usage as kcu1 ON (kcu1.constraint_catalog = rc.constraint_catalog AND kcu1.constraint_schema = rc.constraint_schema AND kcu1.constraint_name = rc.constraint_name)
JOIN information_schema.key_column_usage as kcu2 ON (kcu2.constraint_catalog = rc.unique_constraint_catalog AND kcu2.constraint_schema = rc.unique_constraint_schema AND kcu2.constraint_name = rc.unique_constraint_name AND kcu2.ordinal_position = KCU1.ordinal_position)
WHERE
kcu2.table_name = 'department'
FOR XML PATH('')
);
SELECT @sqlTableConstraints as '8) @sqlTableConstraints';
-- Execute at end
-- 3) Drop outer references for switch (structure must be identical: http://msdn.microsoft.com/en-gb/library/ms191160.aspx) and rename table
SELECT
@sql = (
SELECT
' ALTER TABLE [' + kcu1.constraint_schema + '].' + '[' + kcu1.table_name + '] DROP CONSTRAINT ' + kcu1.constraint_name
FROM information_schema.referential_constraints as rc
JOIN information_schema.key_column_usage as kcu1 ON (kcu1.constraint_catalog = rc.constraint_catalog AND kcu1.constraint_schema = rc.constraint_schema AND kcu1.constraint_name = rc.constraint_name)
JOIN information_schema.key_column_usage as kcu2 ON (kcu2.constraint_catalog = rc.unique_constraint_catalog AND kcu2.constraint_schema = rc.unique_constraint_schema AND kcu2.constraint_name = rc.unique_constraint_name AND kcu2.ordinal_position = KCU1.ordinal_position)
WHERE
kcu2.table_name = @tableName
FOR XML PATH('')
);
SELECT @sql as '3) @sql'
EXECUTE (@sql);
-- 4) Switch partition
-- http://www.calsql.com/2012/05/removing-identity-property-taking-more.html
SET @sql = 'ALTER TABLE ' + @tableName + ' switch partition 1 to ' + @tmpTableName;
SELECT @sql as '4) @sql';
EXECUTE(@sql);
-- 5) Rename real old table to bak
SET @sql = 'EXEC sp_rename ' + @tableName + ', ' + @tableName + '_bak';
SELECT @sql as '5) @sql';
EXECUTE(@sql);
-- 6) Rename temp table to real
SET @sql = 'EXEC sp_rename ' + @tmpTableName + ', ' + @tableName;
SELECT @sql as '6) @sql';
EXECUTE(@sql);
-- 7) Drop bak table
SET @sql = 'DROP TABLE ' + @tableName + '_bak';
SELECT @sql as '7) @sql';
EXECUTE(@sql);
-- 8) Create again doped early constraints
SELECT @sqlTableConstraints as '8) @sqlTableConstraints';
EXECUTE(@sqlTableConstraints);
-- It still may fail if there references from objects with WITH CHECKOPTION
-- it may be recreated - https://stackoverflow.com/questions/1540988/sql-2005-force-table-rename-that-has-dependencies
COMMIT
END
使用非常简单:
EXEC sp_drop_table_identity @tableName = 'some_very_big_table'
利益和限制:
欢迎所有反馈。
答案 4 :(得分:0)
在SQL Server上删除标识列(特别是对于大型数据库)的最有效方法是直接修改DDL元数据,在早于2005的SQL Server上可以使用以下命令:
sp_configure 'allow update', 1
go
reconfigure with override
go
update syscolumns set colstat = 0 --turn off bit 1 which indicates identity column
where id = object_id('table_name') and name = 'column_name'
go
exec sp_configure 'allow update', 0
go
reconfigure with override
go
SQL Server 2005+不支持使用override 进行重新配置,但是当SQL Server实例以单用户模式启动时,您可以执行Ad Hoc查询(使用 -m启动数据库实例) 标志,即“C:\ Program Files \ Microsoft SQL Server \ MSSQL10.MSSQLSERVER \ MSSQL \ Binn \ sqlservr.exe -m”,确保以管理员身份运行,带有专用管理控制台(来自SQL Management Studio connect)使用 ADMIN:前缀,即ADMIN:MyDatabase)。列metdata存储在 sys.sysschobjs 内部表中(未显示DAC):
use myDatabase
update sys.syscolpars set status = 1, idtval = null -- status=1 - primary key, idtval=null - remove identity data
where id = object_id('table_name') AND name = 'column_name'
有关此方法的更多信息on this blog