I believe I have a formatting problem in the query but I need a second set of eyes to help me please.
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 '
I'm expecting:
the select for DomainName to work, as it does if I remove the quotes and hardcode the scaler, but it doesn't inside the dynamic sql. Any ideas? Thanks.
Concatenating string in SQL has a tendency to NULL
the result if any of the values is NULL
. Made a little example you can try:
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'
So, basically you get an empty query, because @Domain is NULL
. For that I suggest to use isnull(@Domain,'')
I overlooked that @Domain is Null. It Shouldn't be and that's the problem. Thank you.