0

在 sql server 上工作。写一个关键 sql,下面是我的表和关键 sql 语法。我的问题是未能将这个关键值放入 Temp 表中。

-----------------Table-1-------------
CREATE TABLE Table1 (ColId INT,ColName VARCHAR(10))
INSERT INTO Table1 VALUES(1, 'Country')
INSERT INTO Table1 VALUES(2, 'MONTH')
INSERT INTO Table1 VALUES(3, 'Day')



----------------Table-2----------------------------

CREATE TABLE Table2 (tID INT,ColID INT,Txt VARCHAR(10))

INSERT INTO Table2 VALUES (1,1, 'US')
INSERT INTO Table2 VALUES (1,2, 'July')
INSERT INTO Table2 VALUES (1,3, '4')
INSERT INTO Table2 VALUES (2,1, 'US')
INSERT INTO Table2 VALUES (2,2, 'Sep')
INSERT INTO Table2 VALUES (2,3, '11')
INSERT INTO Table2 VALUES (3,1, 'US')
INSERT INTO Table2 VALUES (3,2, 'Dec')
INSERT INTO Table2 VALUES (3,3, '25')


--------------
----------------Pivotal sql----------------------------

DECLARE @query NVARCHAR(4000)
DECLARE @cols NVARCHAR(2000)

SELECT  @cols = STUFF(( SELECT DISTINCT TOP 100 PERCENT
                                '],[' + t2.ColName
                        FROM    Table1 AS t2
                        ORDER BY '],[' + t2.ColName
                        FOR XML PATH('')
                      ), 1, 2, '') + ']'                    

SET @query = N'SELECT tID, '+
@cols +'
FROM
(SELECT  t2.tID
      , t1.ColName
      , t2.Txt 
FROM    Table1 AS t1
        JOIN Table2 AS t2 ON t1.ColId = t2.ColID) p
PIVOT
(
MAX([Txt])
FOR ColName IN
( '+
@cols +' )
) AS pvt
ORDER BY tID;'
EXECUTE(@query)

执行下面的命令后,想将此值用于其余工作,所以我需要将此命令结果值放入临时表中

 EXECUTE(@query)
4

2 回答 2

0

尝试这个 :

Declare @Sample table
(
 tID int,
 Country VARCHAR(10),
 Day int ,
 MONTH  VARCHAR(10)
)

Insert into @Sample 
EXECUTE(@query)

select * from @Sample

以同样的方式,您可以创建一个temp table代替table variable并将其插入其中

于 2013-01-17T06:50:30.403 回答
0

如果您能够通过使用 EXECUTE(@Querys) 来完成其余的程序,那么您可以做类似的事情

Declare @TabName Varchar(40)

Select @TabName='##'+Replace(CAST(NEWID() as Varchar(40)),'-','')

DECLARE @query NVARCHAR(4000)
DECLARE @cols NVARCHAR(2000)

SELECT  @cols = STUFF(( SELECT DISTINCT TOP 100 PERCENT
                                '],[' + t2.ColName
                        FROM    Table1 AS t2
                        ORDER BY '],[' + t2.ColName
                        FOR XML PATH('')
                      ), 1, 2, '') + ']'                    

SET @query = N'SELECT tID, '+
@cols +' into ' +@TabName + '
FROM
(SELECT  t2.tID
      , t1.ColName
      , t2.Txt 
FROM    Table1 AS t1
        JOIN Table2 AS t2 ON t1.ColId = t2.ColID) p
PIVOT
(
MAX([Txt])
FOR ColName IN
( '+
@cols +' )
) AS pvt
ORDER BY tID;'

Print @Query
EXECUTE(@query)

Select @query = 'Select * from ' + @Tabname
EXECUTE(@query)

Select @query = 'Drop Table ' + @Tabname
EXECUTE(@query)

如果您不想这样做,您可以使用“硬”##temptable,但您将无法在多用户环境中使用此保存。

于 2013-01-17T06:58:24.440 回答