我有以下脚本,根据第一张图片返回结果集。
脚本:
use your_db_name
declare @tblname nvarchar(max)
set @tblname = 'stockm' --use a table in your database
SELECT
col.column_id
,col.name
,typ.name[type]
,col.max_length
,def.definition
FROM sys.tables tab
INNER JOIN sys.columns col
ON tab.object_id = col.object_id
INNER JOIN sys.default_constraints def
ON col.default_object_id = def.object_id
INNER JOIN sys.types typ
ON col.system_type_id = typ.system_type_id
WHERE (tab.name like @tblname)
ORDER BY col.column_id
结果集:
根据所选表格的结果,我希望在长度上旋转更改。 我这里只展示了前10行,但这个特定的结果集是192行
column_id
name type max_length definition
1 warehouse char 2 (' ')
2 product char 20 (' ')
3 alpha char 10 (' ')
4 description char 20 (' ')
5 supersession char 22 (' ')
6 supsession_date datetime 8 (CONVERT([datetime],'31/12/1899',(103)))
7 alternatives01 char 22 (' ')
8 alternatives02 char 22 (' ')
9 alternatives03 char 22 (' ')
10 value float 8 ((0))
我想将结果转向反映
1 2 ..... 10 to n'th column_id
warehouse product ..... value to n'th name
char char ..... float to n'th type
20 10 ..... 8 to n'th max_length
(' ') (' ') ..... ((0)) to n'th definition
这是我的剧本。它相当接近,但我错过了最后一节(set @query
)
脚本:
declare @cols AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX),
@tblname nvarchar(MAX)
set @tblname = 'stockm'
SELECT @cols = STUFF((
SELECT ',' + QUOTENAME(col.column_id)
FROM
(SELECT DISTINCT col.column_id FROM sys.tables tab
INNER JOIN sys.columns col
ON tab.object_id = col.object_id
WHERE (tab.name like @tblname)) col
ORDER BY col.column_id
FOR XML PATH(''), TYPE).value('.','NVARCHAR(MAX)'),1,1,'')
set @query =
'SELECT ' + @cols + '
FROM(
SELECT
col.column_id
,col.name
,typ.name[type]
,col.max_length
,def.definition
FROM sys.tables tab
INNER JOIN sys.columns col
ON tab.object_id = col.object_id
INNER JOIN sys.default_constraints def
ON col.default_object_id = def.object_id
INNER JOIN sys.types typ
ON col.system_type_id = typ.system_type_id
WHERE tab.name like ''' + @tblname +''') x
PIVOT
(
max(column_id)
for column_id in (' + @cols + ')
) p'
) p
print (@query)
execute (@query)
我将不胜感激。