使用exec sp_execute的null结果


我有一些动态SQL,用于查看某个客户端的某个属性是否在表中。如果是,则返回值;如果不是,则返回null。但是,如果找不到该属性,我希望它返回默认值。

下表:

CREATE TABLE [test].[customers](
    [customer] [nvarchar](256) NULL,
    [key_name] [nvarchar](256) NULL,
    [key_value] [nvarchar](256) NULL
) 
GO


INSERT INTO [test].[customers]
           ([customer]
           ,[key_name]
           ,[key_value])
     VALUES
           ('JohnDoe'
           ,'periodlength'
           ,'3')
GO

动态SQL:

declare @customer as nvarchar(256) = 'JohnDoe'
declare @table as nvarchar(256) = 'test.customers'

declare @sql as nvarchar(4000)
set @sql = 'select [key_value] from ' +  @table + ' where [key_name]= ''periodlength'' and customer= ''' + @customer + ''''
exec sp_executesql @sql

所以,当你对无名氏进行查询时,你得到的结果是3,这很完美。但是,我想为无名氏返回1。所以我沿着IF exec sp_executesql @sql IS NULL 1 ELSE exec sp_executesql @sql的思路思考,但这不起作用。

如何更改我的动态查询,以便在未找到属性时返回默认值?

转载请注明出处:http://www.beijingklxcmc.com/article/20230526/1371086.html