gpt4 book ai didi

sql-server - 处理 SQL 中字符串内的 IS NULL

转载 作者:行者123 更新时间:2023-12-03 12:50:26 24 4
gpt4 key购买 nike

我有一个以字符串形式编写的 SQL 查询,然后使用命令 Exec(string) 执行,如下所示:

Declare @TestId bigint = null
Declare @Query nvarchar(max)
set @Query = 'SELECT * from Registrations where RegistrationId = 15 AND (' + CAST(@TestId AS NVARCHAR) + ' IS NULL OR TestId = ' + CAST(@TestId AS NVARCHAR) + ') '
EXEC(@Query)

现在的问题是 IS NULL 没有在字符串中正确解析,但是当我从字符串中删除 IS NULL 时,它可以正常工作,并且当 @TestId 采用 null 以外的值时,它可以在问题所在的位置正常工作@Query 字符串内 IS NULL 的转换。

注意:@TestId是一个过程参数

我需要知道如何让 SQL 感觉为 IS NULL 并正确解析它

提前致谢

最佳答案

如果您确实需要为此使用动态 sql,请像这样使用 sp_executesql:

Declare @TestId bigint = null
Declare @Query nvarchar(max)
set @Query = 'SELECT * from Registrations where RegistrationId = 15 AND (@TestId IS NULL OR TestId = @TestId)'

EXECUTE sp_executesql @Query, N'@TestId BIG INT', @TestId

关于sql-server - 处理 SQL 中字符串内的 IS NULL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3708877/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com