如何动态生成表名
use pubs
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[testxxx]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
begin
insert into testxxx
select * from authors
end
else
begin
select * into testxxx from authors
end
我希望表testxxx是动态生成的后面加上当前时间,
也就是说
2012-12-18 15:50执行时testxxx应该是testxxx201212181550
请问这要怎么写
[解决办法]
use pubs
go
declare @tbname nvarchar(20),@sql nvarchar(4000)
select @tbname='test'+replace(replace(replace(convert(varchar(17),getdate(),120),'-',''),' ',''),':','')
if exists (select * from dbo.sysobjects where id = object_id(@tbname) and OBJECTPROPERTY(id, N'IsUserTable') = 1)
set @sql='insert into '+@tbname+' select * from authors'
else
set @sql='select * into '+@tbname+' from authors'
execute(@sql)