温馨提示:本文翻译自stackoverflow.com,查看原文请点击:ssms - Why won't my query in a dynamic SQL work as intended?
sql ssms

ssms - 为什么我在动态SQL中的查询无法按预期工作?

发布于 2020-03-27 10:32:16

我相信查询中存在格式问题,但是我需要另一只眼睛来帮助我。

select @InsertSQL = ' Insert Into #ResultSet('
    +   'UserDomainMappingId,'
    +   'UserId,'
    +   'UserName,'
    +   'Domain,'
    +   'DomainName,'
    +   'LastUpdatedBy,'
    +   'LastUpdatedByName,'
    +   'LastUpdatedAt)'

select @SelectSQL = ' select '
    +   'UD.UserDomainMappingId,'
    +   'UD.UserId,'
    +   '(select FullName from Users where UserId = UD.UserId),'
    +   'UD.Domain,'
    +   '(select Name from ReferenceCodes RC where RC.Type = ''DOMAIN'' and RC.Code = ''' + @Domain + '''),'
    +   'UD.LastUpdatedBy,'
    +   '(select FullName from Users where UserId = UD.LastUpdatedBy),'
    +   'UD.LastUpdatedAt'                              

    select @FromSQL = ' from UserDomainMapping UD '

    select @WhereSQL = 'where UserDomainMappingId = UD.UserDomainMappingId '

我期待着:

选择域名以使其正常工作,就像我删除引号并对定标器进行硬编码一样,但它不在动态sql内。有任何想法吗?谢谢。

查看更多

查看更多

提问者
H22
被浏览
207
lakta 2019-07-03 22:14

NULL如果任何值是,则SQL中的串联字符串都有可能产生结果NULL作了一个小例子,您可以尝试:

declare @A varchar(100), @B varchar(100), @C varchar(100)

set @A = 'a'
set @B = 'b'
set @C = @A + @B 
select @C --'ab' 

set @A = null
set @B = 'b'
set @C = @A + @B 
select @C --NULL 

set @A = 'a'
set @B = null
set @C = @A + @B 
select @C --NULL 

set @A = 'a'
set @B = null
set @C = @A + isnull(@B ,'')
select @C --'a'

因此,基本上您会得到一个空查询,因为@Domain是NULL为此,我建议使用isnull(@Domain,'')