我需要检查mytable
表是否包含mycolumn
列?这是我的疑问:
SELECT CASE WHEN EXISTS (SHOW COLUMNS FROM mytable LIKE mycolumn) THEN 1 ELSE 0 END;
但它不起作用并抛出此错误消息:
#1064 - 您的SQL语法出错;检查与MySQL服务器版本对应的手册,以获得正确的语法 在'mytable LIKE mycolumn'附近'SHOW COLUMNS'那么在第1行结束0结束
出了什么问题,如何解决?
答案 0 :(得分:4)
您可以将以下内容用作if
IF EXISTS(
select * from
INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME ='SOMETABLE' AND
COLUMN_NAME = 'SOMECOLUMN')
)
BEGIN
-- do stuff
END
GO
或者作为案例
SELECT CASE WHEN EXISTS(
select * from
INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME ='TABLE_NAME' AND
COLUMN_NAME = 'COLUMN_NAME')
Then 1 Else 0 End;
答案 1 :(得分:3)
试试这个
SELECT CASE WHEN EXISTS (
SELECT * FROM information_schema.COLUMNS
WHERE TABLE_SCHEMA = 'db_name'
AND TABLE_NAME = 'table_name'
AND COLUMN_NAME = 'column_name')
then 1
else 0
end;
答案 2 :(得分:1)
如果您需要动态传递表名和列名,请使用此名称。
DECLARE @Table Varchar(100)
DECLARE @Column Varchar(100)
DECLARE @Query nvarchar(max)
SET @Table ='MyTable'
SET @Column ='MyColumn'
SET @Query ='select * from
INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME ='''+@Table+''' AND
COLUMN_NAME IN ('''+@Column+''')'
EXEC (@Query)