我想在MS-SQL上创建临时表,但是要通过其他行数据创建
表X
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
========================================================
非常感谢。
答案 0 :(得分: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
----------- ----------- ----------- ----------- ----------- -----------