使用 exec sp_execute 的空结果

Use null result of exec sp_execute

我有一些动态 SQL,我用它来查看某个客户的某个 属性 是否在 table 中。如果是,它将 return 值,如果不是,它将 return 为空。但是,如果找不到 属性,我希望它成为 return 默认值。

table:

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

因此,当 Qqerying 为 John Doe 时,您会得到完美的结果 3。但是,我想为 Jane Doe 返回 1。所以我一直在想 IF exec sp_executesql @sql IS NULL 1 ELSE exec sp_executesql @sql 但这不起作用。

如果找不到 属性,如何更改我的动态查询以便将 return 设置为默认值?

你能试试下面的查询吗,但是这个用法只return一个单一的值;

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

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

    BEGIN 
    IF @ValReturn IS NULL
    SELECT NULL
    ELSE
    SELECT @ValReturn
    END