真心求高手来帮我补充一下这个SQL语句,往下不会写了,真的需要高手,版主来看看吧。需求很BT。关于自动生成SQL语句的
本帖最后由 wdzczy 于 2013-01-22 20:13:09 编辑 看下代码,是否能理解我要表达的意思:
--是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 left join sys.identity_columns b on a.object_id = b.object_id
where schema_id = schema_id('dbo')
declare @sql varchar(8000)
WHILE exists(select * from #ta)
BEGIN
set @sql = ''
select top(1) @sql = IdentityOn + ' insert into ' + name + '(' + longname + ') select ' + longname + ' From [服务名].数据库名.dbo.'+ name + IdentityOff
from #ta order by name
print @sql
;with cet as( select top(1)* from #ta order by name )
delete cet
END
drop table #ta
GO
/*
set identity_insert aaa on insert into aaa(id,b) select id,b From [服务名].数据库名.dbo.aaa set identity_insert aaa off
insert into c1(a,b,c) select a,b,c From [服务名].数据库名.dbo.c1
insert into cangku(id,cangku,tmpA,tmpB,inPrice,allNum,allprice) select id,cangku,tmpA,tmpB,inPrice,allNum,allprice From [服务名].数据库名.dbo.cangku
insert into huang(manIds) select manIds From [服务名].数据库名.dbo.huang
insert into Novel(T) select T From [服务名].数据库名.dbo.Novel
insert into Nums(n) select n From [服务名].数据库名.dbo.Nums
*/