Click here to Skip to main content
15,916,458 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
>Hi there, below is an if statement in which I want to populate the table result within a table called #t for which ever statement is true.
How do I do this? The below does not seem to work:
SQL
SET @OpenQuerySql = 'IF  (' + cast(@FirstTableMonth as varchar) + '+99) = CONVERT(nvarchar(6), dateadd(month,-1,GETDATE()), 112)
BEGIN
		 SELECT *
		FROM OPENQUERY(['+ @LinkedServerName +'], '''+ @DynamicSQL + ''' ) 
UNION ALL 
	*
into #t					
FROM #temp
END
else 
begin 
SELECT ACCT_NO,
		*
		FROM OPENQUERY(['+ @LinkedServerName +'], '''+ @DynamicSQL + ''' ) 
into #t	
UNION ALL 
SELECT ACCT_NO,
		*
		FROM OPENQUERY(['+ @LinkedServerName +'], '''+ @DynamicSQL2 + ''' ) 
end
'
Posted
Updated 11-Sep-22 19:17pm
v2
Comments
Tomas Takac 23-Nov-15 9:31am    
What do you mean by "it doesn't work"? Is there an error? The part with "UNION ALL * into #t" at lines 6-8 seems wrong.

1 solution

There are several issues with your code but the easiest way to find them is to put a PRINT @OpenQuerySql in place of the EXEC - that way you can use the built-in error reporting in SSMS to help you locate the errors.

In this case, you have missed a SELECT before the first UNION ALL and you are not handling the insert into #t correctly for a UNION query.

Try this
SQL
SET @OpenQuerySql = 'IF  (' + cast(@FirstTableMonth as varchar) + '+99) = CONVERT(nvarchar(6), dateadd(month,-1,GETDATE()), 112)
BEGIN
   SELECT * INTO #t FROM 
   (
	SELECT *
	FROM OPENQUERY(['+ @LinkedServerName +'], '''+ @DynamicSQL + ''' ) 
	UNION ALL 
	SELECT * FROM #temp
) as tmp
END
else 
begin 
	SELECT * INTO #t FROM 
	(
	
		SELECT ACCT_NO, *
		FROM OPENQUERY(['+ @LinkedServerName +'], '''+ @DynamicSQL + ''' ) 
		UNION ALL 
		SELECT ACCT_NO, *
		FROM OPENQUERY(['+ @LinkedServerName +'], '''+ @DynamicSQL2 + ''' ) 
	) as tmp
end
'
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900