我想要列数据类型,如果数据类型为int,则显示列名,如果varchar,则在水平行外星人中显示带有''的列名
我尝试了类似的操作,但不知道如何应用条件:
SELECT
t.Name 'Data type'
FROM
sys.columns c
INNER JOIN
sys.types t ON c.user_type_id = t.user_type_id
where object_id = OBJECT_ID('tbl_Check_Sql_Query')
假设我的列的数据类型为
id int
name varchar
Email_ID varchar
然后我想要
id,'name','Email_ID'
答案 0 :(得分:4)
您可以直接将 INFORMATION_SCHEMA.COLUMNS
系统视图用作
SELECT TABLE_NAME,
CASE DATA_TYPE WHEN 'INT' THEN COLUMN_NAME
--WHEN 'VARCHAR' I don't know what you mean by "in horizontal line alien"
END
FROM INFORMATION_SCHEMA.COLUMNS;
--WHERE TABLE_NAME = 'TableName'
或
SELECT TABLE_NAME,
STRING_AGG(CASE WHEN DATA_TYPE = 'VARCHAR'
THEN QUOTENAME(COLUMN_NAME, '''')
ELSE COLUMN_NAME
END, ',') Columns
FROM INFORMATION_SCHEMA.COLUMNS
GROUP BY TABLE_NAME;
--WHERE TABLE_NAME = 'TableName'
或
SELECT TABLE_NAME,
STUFF(
(SELECT ',' + CASE WHEN DATA_TYPE = 'VARCHAR'
THEN QUOTENAME(COLUMN_NAME, '''')
ELSE COLUMN_NAME
END
FROM INFORMATION_SCHEMA.COLUMNS T2
WHERE T1.TABLE_NAME = T2.TABLE_NAME
FOR XML PATH('')
), 1, 1, ''
) Columns
FROM INFORMATION_SCHEMA.COLUMNS T1
GROUP BY TABLE_NAME;
更新:
由于您试图在数据类型为GETDATE()
时返回DATETIME
值,因此
SELECT TABLE_NAME,
STUFF(
(SELECT ',' + CASE DATA_TYPE WHEN 'VARCHAR'
THEN QUOTENAME(COLUMN_NAME, '''')
WHEN 'DATETIME'
THEN 'GETDATE()'
ELSE COLUMN_NAME
END
FROM INFORMATION_SCHEMA.COLUMNS T2
WHERE T1.TABLE_NAME = T2.TABLE_NAME
FOR XML PATH('')
), 1, 1, ''
) Columns
FROM INFORMATION_SCHEMA.COLUMNS T1
GROUP BY TABLE_NAME;