如何声明具有动态列数的临时/变量表

时间:2018-11-13 13:39:09

标签: sql sql-server tsql

我有这样的桌子:

Table Name|Number of columns

如何在存储过程内部动态创建临时表,其中临时表的名称来自第一个表,而变量列的名称例如col1,col2等。 我还需要向其中插入值,并对它们进行其他逻辑处理。

示例:

Table1|3

Table1(col1 nvarchar(max), col2 nvarchar(max), col3 nvarchar(max))

2 个答案:

答案 0 :(得分:0)

您将需要使用如下所示的动态sql:

declare @counter int = 1
declare @numberOfCols int = 3 -- OR you can use ->(select numberofcolumns from firsttable)
declare @dynamic nvarchar(max) = ''
declare @sql nvarchar(max) = 'CREATE TABLE #TEMP (';

while @counter <= @numberofCols
begin
   set @dynamic = @dynamic + 'col'+cast(@counter as nvarchar(5))+' nvarchar(max) ';   
   if(@counter <> @numberOfCols)
   begin
      set @dynamic = @dynamic + ', ';
   end 
   set @counter = @counter + 1
end

set @sql = @sql + @dynamic + ') select * from #temp'
select @sql

EXECUTE sp_executesql @sql

答案 1 :(得分:0)

I have created a stored procedure regarding your question. I wish it can help you.

ALTER PROCEDURE P_ProcedureName
    @NumberOfColumns    INT=2 --expected 1 or more column

AS

DECLARE @SQLString  VARCHAR(MAX)=''
DECLARE @Seq        INT=2

IF @NumberOfColumns=0 
BEGIN
    SELECT 'Please add valid number of column'
    RETURN
END

CREATE TABLE #Table
(
     Id INT NOT NULL    IDENTITY(1,1)
    ,Column1            VARCHAR(MAX)
)


WHILE @Seq<=@NumberOfColumns
BEGIN
    SET @SQLString=@SQLString+'ALTER TABLE #Table ADD Column'+CAST(@Seq AS VARCHAR)+' VARCHAR(MAX)'+char(13)
    PRINT(@SQLString)
    SET @Seq +=1
END
EXEC(@SQLString)

SELECT * FROM #Table

GO


P_ProcedureName 5