如果列存在则执行一个查询 - 否则执行另一个查询

时间:2013-11-28 09:14:59

标签: sql sql-server sql-server-2008-r2

我正在尝试检查列VATNO是否存在。如果该列存在,则版本为4.8,然后我想执行该查找。否则它是一个较低的版本,然后我想执行另一个查询。

if exists(select * from sys.columns 
            where Name = N'VATNO' and Object_ID = Object_ID(N'COMPANIES'))
BEGIN

/* If version is 4.8 */
SELECT [NO], [DESCRIPTION] FROM COMPANIES WHERE VATNO <> '' ORDER BY [NO]

END

ELSE
BEGIN

/* If under version 4.8 */
SELECT [NO], [DESCRIPTION] FROM COMPANIES ORDER BY [NO]

END ;

这会返回以下错误:

  

Msg 207,level 16,State 1,Line 6
  列名称'VATNO'无效

我正在运行SQL Server 10.50.1600

提前感谢您的帮助。

2 个答案:

答案 0 :(得分:3)

这将是一个编译时错误。您将需要使用动态SQL来解决此问题。

DECLARE @SQL nvarchar(2000);
IF EXISTS(SELECT NULL FROM sys.columns 
            WHERE Name = N'VATNO' and Object_ID = Object_ID(N'DBO.COMPANIES'))
BEGIN

/* If version is 4.8 */
SET @SQL = 'SELECT [NO], [DESCRIPTION] FROM COMPANIES WHERE VATNO <> '''' ORDER BY [NO]'

END

ELSE
BEGIN

/* If under version 4.8 */
SET @SQL = 'SELECT [NO], [DESCRIPTION] FROM COMPANIES ORDER BY [NO]'

END ;
EXEC sp_executesql @SQL

此外,在调用object_id()时,最好包含架构

答案 1 :(得分:1)

动态SQL查询是摆脱这种情况的方法:

IF ((SELECT count(name) FROM sys.columns WHERE name= 'VATNO') > 0)
BEGIN 
DECLARE @sql NVARCHAR(MAX);
SET @sql = N'  SELECT foobar FROM companies where VATNO <> '' ORDER BY [NO]';
EXEC sp_executesql @sql;
END
ELSE
begin
SELECT [NO], [DESCRIPTION] FROM COMPANIES ORDER BY [NO]
END;