我想执行SELECT,只有在表中存在该列时才会选择列值,否则显示为null。
这就是我目前正在做的事情:
SELECT TOP 10 CASE WHEN EXISTS
(SELECT * FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA ='test' and TABLE_NAME='tableName' and COLUMN_NAME='columnName')
THEN columnName ELSE NULL END AS columnName
我也试过这个:
SELECT TOP 10 CASE WHEN
(SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA ='test' and TABLE_NAME='tableName' and COLUMN_NAME='columnName') >0
THEN columnName ELSE NULL END AS columnName
如果列中存在列,它们都可以正常工作。但是当列不存在时,它会给我错误:
列名称无效' columnName'
答案 0 :(得分:5)
你可以写成:
SELECT CASE WHEN EXISTS
(
SELECT * FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA ='test' and TABLE_NAME='tableName'
and COLUMN_NAME='columnName'
)
THEN
(
SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA ='test' and TABLE_NAME='tableName'
and COLUMN_NAME='columnName'
)
ELSE
NULL
END
AS columnName
编辑: 如果您希望从表的列中选择前10个值(如果该列存在),则需要将动态查询编写为:
SELECT @columnVariable =
CASE WHEN EXISTS
(
SELECT * FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA ='test' and TABLE_NAME='tableName'
and COLUMN_NAME='columnName'
)
THEN
(
SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA ='test' and TABLE_NAME='tableName'
and COLUMN_NAME='columnName'
)
ELSE
NULL
END
/* Build the SQL string one time.*/
SET @SQLString =
N'SELECT TOP 10 ' + @columnVariable+ '
FROM test.tableName ';
EXECUTE sp_executesql @SQLString
答案 1 :(得分:0)
试试这个:
SELECT
TOP 1
CASE
WHEN COLUMN_NAME='columnName' THEN
COLUMN_NAME
ELSE
NULL
END
AS COLUMN_NAME
FROM
INFORMATION_SCHEMA.COLUMNS
WHERE
TABLE_SCHEMA ='test' and TABLE_NAME='tableName'
ORDER BY
COLUMN_NAME DESC
答案 2 :(得分:0)
SELECT *
FROM sys.columns
WHERE [name] = N'columnName'
AND [object_id] = OBJECT_ID(N'tableName')
在case语句中添加它。请注意,此代码仅适用于更高版本的sqlserver。[如sqlserver 2008]