我遇到使用动态查询的问题,如下所示:
Declare @SQL1 varchar(max)
Set @SQL1 = '
Insert into #TEMPSelect
SELECT DISTINCT tbAgent.Agent,
...
...,
case when coalesce(tbsystemuser.MiddleName, '''') = '''' then tbsystemuser.FirstName + '' '' + tbsystemuser.LastName
else tbsystemuser.FirstName + '' '' + tbsysten.MiddleName + '' '' + tbsystemuser.LastName end,
tbsystemuser.EmailAddress,
tbagent.AgentCode,
tbBroker.businessname
FROM tbSystemUser
inner JOIN dbo.tbAgent
ON tbSystemUser.SystemUser=tbAgent.SystemUser
WHERE (tbagent.DeletionIndicator=0 and tbsystemuser.SystemRoleType!=10 ) '
If LEN (@Name) >1
Set @SQL1 = @SQL1 + 'and FullName LIKE ''' + @Name + ''''
Exec(@SQL1)
它没有任何回报!我认为这个问题归因于coalesce
行和'' ''
答案 0 :(得分:2)
试试这个,
DECLARE @SQL1 VARCHAR(max) = ''
,@Name VARCHAR(100) = 'test'
SET @SQL1 = 'INSERT INTO #TEMPSelect
SELECT DISTINCT tbAgent.Agent
,CASE
WHEN coalesce(tbsystemuser.MiddleName, '''') = ''''
THEN tbsystemuser.FirstName + '' '' + tbsystemuser.LastName
ELSE tbsystemuser.FirstName + '' '' + tbsysten.MiddleName + '' '' + tbsystemuser.LastName
END AS FULLNAME
,tbsystemuser.EmailAddress
,tbagent.AgentCode
,tbBroker.businessname
FROM tbSystemUser
INNER JOIN dbo.tbAgent ON tbSystemUser.SystemUser = tbAgent.SystemUser
WHERE (
tbagent.DeletionIndicator = 0
AND tbsystemuser.SystemRoleType != 10
)'
IF LEN(@Name) > 1
SET @SQL1 = @SQL1 + 'and FullName LIKE ''%' + @Name + '%'''
EXEC (@SQL1)
正如Arulkumar所说,你应该为case语句给出别名。除此之外,在类似声明中使用%