Creating a temporary table name with a randomly generated number

安稳与你 提交于 2019-12-13 13:56:37

问题


So far I have this code:

declare @random int, @upper int, @lower int, @rndtb varchar(20)
set @lower = 1
set @upper = 999
select @random = ROUND(((@upper - @lower) * rand() + @lower),0)
select @rndtb = '##show'+cast(@random as varchar(20))+''

But that gives me

Conversion failed when converting the varchar value '##show' to data type int.

What I am trying to achieve is to create a table ##show+random number each time the query is executed.

Example :

##show01
##show78
##show43

Edited with what @bluefeet said and found a way to create the table with

Declare @SQL VarChar(1000)

SELECT @SQL = 'Create Table ' + @rndtb + '('
SELECT @SQL = @SQL + 'ID int NOT NULL Primary Key, FieldName VarChar(10))'

Exec (@SQL)

but how do I call or insert into this table?


回答1:


Since you are adding the parameter @random to a string, you need to cast it as a varchar so it can be concatenated to the string portion:

select @rndtb = '##show'+cast(@random as varchar(20))+''

Your full code will be:

declare @random int, @upper int, @lower int, @rndtb varchar(20)
set @lower = 1
set @upper = 999
select @random = ROUND(((@upper - @lower) * rand() + @lower),0)
select @rndtb = '##show'+cast(@random as varchar(20))+''

Based on your edit, you will need to use dynamic sql to insert into the new table:

select @SQL = 'insert into '+@rndtb+'
        select *
        from yourtable'


exec (@sql)



回答2:


use this:

select @rndtb = '##show'+CONVERT(VARCHAR(20), @random, 0)



回答3:


You need dynamic SQL

The Curse and Blessings of Dynamic SQL

http://www.sommarskog.se/dynamic_sql.html



来源:https://stackoverflow.com/questions/14756780/creating-a-temporary-table-name-with-a-randomly-generated-number

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!