troubleshooting Question

How to add Case statement in Dynamic sql Select statement

Avatar of KavyaVS
KavyaVS asked on
Microsoft SQL Server 2008
11 Comments2 Solutions308 ViewsLast Modified:
Create procedure dbo.usp_GetDetails as BEGIN
DECLARE @sql nvarchar(4000);
 Declare @table1 varchar(2000), @pdt datetime
set @pdt = DATEADD(d, -day(getdate())+1, getdate())

@table1 = SSQLARCHIVE_' + Convert(Varchar(4),year(@pdt)) +'.dbo.t_accounthistory' + Right('0'+Convert(Varchar,month(@pdt)), 2)
SELECT @sql= 'SELECT  Distinct de.ID
     ,CASE WHEN (md.RECORDTYPE = ''2'') AND (md.FIELDNUMBER IN (''15'', ''16'', ''17'', ''18'', ''19'') AND (md.FMTYPE = ''1'') AND (md.IDTYPE =''2'') AND (md.OLDCHARACTER <> '''')THEN ADDRESSCHANGE
            WHEN (md.RECORDTYPE = ''2'') AND (md.FIELDNUMBER IN (''8'') AND (md.FMTYPE = ''1'') THEN CARDACTIVITY
            ELSE (dbo.fn_GetDetails(md.RECORDTYPE, md.FIELDNUMBER, md.SUBFIELDNUMBER))
            END AS Details
      ,md.DATE As DetailsDATE
FROM ' + @table1 +  ' md with (noLock)  Inner Join #Temp_List de  with (noLock)
  ON  md.[ID] = de.ID
 Print @sql
  EXECUTE  sp_executesql @sql
    Drop Table #Temp_List;

I am getting the error.
Incorrect syntax near the keyword 'THEN'.

How to fix it.

David Kroll
Sr. Delphi Consultant

Our community of experts have been thoroughly vetted for their expertise and industry experience.

Join our community to see this answer!
Unlock 2 Answers and 11 Comments.
Start Free Trial
Learn from the best

Network and collaborate with thousands of CTOs, CISOs, and IT Pros rooting for you and your success.

Andrew Hancock - VMware vExpert
See if this solution works for you by signing up for a 7 day free trial.
Unlock 2 Answers and 11 Comments.
Try for 7 days

”The time we save is the biggest benefit of E-E to our team. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange.

-Mike Kapnisakis, Warner Bros