使用过程从另一个表创建一个动态临时表具有单个列

时间:2015-08-15 06:50:27

标签: sql-server sql-server-2008 stored-procedures

我想从另一个表创建一个临时表,动态创建存储过程。

我有一个名为Tblstructure的表。此表只有1列Colname。列中的数据是在运行时创建的,并且每次都会更改。暂时我有数据

Colname
-------
Region
Country
State
Metric
Value

我想使用上面的表并创建一个动态表,其列为

Region  Country  state  Metric  value.

每当用户调用存储过程时,过程调用表tblstructure从表中拉出所有行并将它们转换为列标题。

怎么做?

1 个答案:

答案 0 :(得分:0)

I think what you need to look into are patterns for concatenating text stored across the rows in a table. This resource lays out some common patterns you should read about: https://www.simple-talk.com/sql/t-sql-programming/concatenating-row-values-in-transact-sql/

That said, the XML path pattern is the one I most frequently employ.

CREATE TABLE Tblstructure (Colname varchar(50));

INSERT INTO Tblstructure (Colname)
VALUES ('Region'), ('Country'), ('State'), ('Metric'), ('Value');

DECLARE @ColumnDeclaration VARCHAR(2000) =
    STUFF(
        (SELECT ', ' + Colname + ' VARCHAR(50) '
         FROM Tblstructure
         FOR XML PATH(''), type).value('.', 'varchar(max)')
    , 1, 1, '')

SELECT 'CREATE TABLE SomeTempTable (' + @ColumnDeclaration + ');'

Output: CREATE TABLE SomeTempTable ( Region VARCHAR(50) , Country VARCHAR(50) , State VARCHAR(50) , Metric VARCHAR(50) , Value VARCHAR(50) );

Notice that I had to make an assumption about the type that should represent each field. I have assumed each field is a VARCHAR(50), but you would probably want to figure out a better way of inferring what type each field should be.

Working example: http://sqlfiddle.com/#!6/d4434/23

Edit

Also, keep in mind that this example wouldn't actually create the table, it just gives you the dynamic create table statement. To execute this, you would want to feed the resulting create table statement into sp_executesql.