日期:2014-05-17 浏览次数:20390 次
--是sql2008的环境
DECLARE @table VARCHAR(64)
SET @table = '这里需要动态生成DBO类型的表名'--这里又怎么写?
DECLARE @name VARCHAR(128),@longname VARCHAR(1024)
SET @name = ''
SET @longname = ''
DECLARE cur CURSOR FOR
SELECT s.name +',' FROM sys.syscolumns s
INNER JOIN sysobjects s2 ON s.id=s2.id
WHERE s2.name = @table
OPEN cur
FETCH NEXT FROM cur INTO @name
WHILE @@FETCH_STATUS = 0
BEGIN
set @longname = @longname + @name
FETCH NEXT FROM cur INTO @name
END
SET @longname = LEFT(@longname,LEN(@longname)-1)
--if(DB1数据库内的某些表含有主键)---求这条语句
执行以下SQL语句
PRINT ' set identity_insert '+@table +' on insert into ' + @table + '(' + @longname + ') select '+'' + @longname + ''+ ' From [服务名].数据库名.dbo.' + @table +' set identity_insert '+@table +' off '
--if(不包含主键)---求这条语句
--则执行以下SQL语句
--SQL语句我暂时省略了
CLOSE cur
DEALLOCATE cur
DECLARE @s NVARCHAR(4000)
SET @s = ''
SELECT @s = @s + ',' + QUOTENAME(name)
FROM syscolumns
WHERE id = OBJECT_ID('表名')
AND name NOT IN ( '不希望显式的列' )
SET @s = STUFF(@s, 1, 1, '')
EXEC('select '+@s+' from 表名 ')
Set NOCOUNT ON
select
case when b.column_id is null then '' else ' set identity_insert '+a.name +' on ' end as IdentityOn,
a.name,
stuff((select ','+b.name from sys.syscolumns b
where a.object_id = b.id
order by b.id,b.colorder
for xml path('') ) ,1,1,'') longname ,
case when b.column_id is null then '' else ' set identity_insert '+a.name +' off ' end as IdentityOff
into #ta
from sys.tables a