2

我想在 MS-SQL 上创建临时表,但由其他行数据创建

表十

FieldA 
=======
SkillA
SkillB
SkillC

温度表

SkillA     SkillB    SkillC
============================
Null         Null       Null

谢谢你的帮助

我想在服务器端执行。而且我不知道数量行数据。我展开。

TABLE X
FieldA    FieldB
===================
 SKillA    SubjectA
 SkillB    SubjectB
 SkillC    SubjectC
...
...
*** I don't know amount row data ***

Temp Table
SkillA   SubjectA   SkillB   SubjectB  SkillC  SubjectC
========================================================

非常感谢。

4

1 回答 1

3

试试这个——

询问:

IF OBJECT_ID (N'tempdb.dbo.#temp') IS NOT NULL
   DROP TABLE #temp

DECLARE @temp TABLE (FieldA NVARCHAR(50))
INSERT INTO @temp (FieldA)
VALUES 
    ('SkillA'),
    ('SkillB'),
    ('SkillC')

SELECT *
INTO #temp
FROM (
    SELECT FieldA, a = CAST(NULL AS INT) 
    FROM @temp
) src
PIVOT 
(
    MAX(a) 
    FOR FieldA IN (SkillA, SkillB, SkillC)
) unpvt

SELECT * 
FROM #temp t

输出:

SkillA      SkillB      SkillC
----------- ----------- -----------
NULL        NULL        NULL

更新 2:我不知道金额行数据

询问:

IF OBJECT_ID (N'tempdb.dbo.##temp') IS NOT NULL
   DROP TABLE ##temp

DECLARE @temp TABLE (FieldA VARCHAR(20), FieldB VARCHAR(20))
INSERT INTO @temp (FieldA, FieldB)
VALUES 
    ('SKillA', 'SubjectA'),
    ('SkillB', 'SubjectB'),
    ('SkillC', 'SubjectC')

DECLARE @SQL NVARCHAR(MAX)
SELECT @SQL = '
    SELECT * 
    INTO ##temp 
    FROM (
    SELECT ' + STUFF((
    SELECT DISTINCT ', [' + FieldA + '] = NULL, [' + FieldB + '] = NULL'
    FROM @temp
    FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 2, '') + ') t 
    WHERE 1 != 1'

EXEC sys.sp_executesql @SQL

SELECT * 
FROM ##temp t

输出:

SKillA      SubjectA    SkillB      SubjectB    SkillC      SubjectC
----------- ----------- ----------- ----------- ----------- -----------
于 2013-06-13T13:10:53.560 回答