为什么我的 Dynamic SQL 在检查非空条件时出错?

Why does my Dynamic SQL error out while checking not null condition?

我正在尝试将 country_name 和 country_code 列 In my country table 作为变量传递。如果条件成立,我想 return 1。

SELECT  @Column1 = N'country_name'
SELECT  @Column2 = N'country_code'

SELECT @sql = N'SELECT ' +'1' +' FROM country where' + @Column1 + 'is not null and' + @Column2 + 'is not null'
EXEC sp_executesql @sql

错误代码:

Msg 156, Level 15, State 1, Line 1418 Incorrect syntax near the keyword 'not'.

有人可以帮我解决这个问题吗?

看起来您可能缺少@Column1 和@Column2 前后的一些空格。即,您当前的 SQL 看起来有点像这样对吧?

'SELECT 1 FROM country wherecountry_nameis not null andcountry_codeis not null'

如下更新应该可以达到我想象的效果:

SELECT  @Column1 = N'country_name'
SELECT  @Column2 = N'country_code'

SELECT @sql = N'SELECT ' + '1' + ' FROM country where ' + @Column1 + ' is not null and ' + @Column2 + ' is not null'
EXEC sp_executesql @sql