Click here to Skip to main content
16,004,782 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi there,

I am using dynamic sql and I am trying to perform a 'where in' from another table, however I am having syntax issues.

What I have tried:

SQL
DECLARE @accountprofit nvarchar(max)
DECLARE @accountprofit2 nvarchar(max)
DECLARE @accountprofile nvarchar(max)
DECLARE @accountprofile2 nvarchar(max)


set @accountprofit = 'select cust_no from G.DBO.Clients'
EXEC(@accountprofit)


SET @accountprofile2 = 'SELECT ACC,
CUST
FROM ACCOUNTTABLE   AP
WHERE ap.cust in ('  + @accountprofit +  ') '

exec @accountprofile2

SET @accountprofile = 'SELECT * into ##accountprofile FROM OPENQUERY([MYSERVER],' + '''' + @accountprofile2 + '''' + ')'

EXEC(@accountprofile)

select * from ##accountprofile
Posted
Updated 3-Sep-16 12:13pm
v2
Comments
Suvendu Shekhar Giri 3-Sep-16 7:04am    
What error it is showing?

1 solution

Without your schema (i'm to lazy to reverse engineer using var tables) this is going to be a bit difficult to be sure.

When placed into one variable, your sql looks to compile down to this

SQL
SELECT * into ##accountprofile FROM OPENQUERY([MYSERVER],'SELECT ACC,CUST FROM ACCOUNTTABLE AP WHERE ap.cust in (select cust_no from G.DBO.Clients)')


My best guess is that your SELECT statement beside [MYSERVER] has been placed in there as a string, instead it needs to look like

SQL
SELECT * into ##accountprofile FROM OPENQUERY([MYSERVER],(SELECT ACC,CUST FROM ACCOUNTTABLE AP WHERE ap.cust in (select cust_no from G.DBO.Clients)))


To achieve this you would do the following in your @accountprofile variable.

SQL
SET @accountprofile = 'SELECT * into ##accountprofile FROM OPENQUERY([MYSERVER], (' + @accountprofile2 + '))'


Should this not solve your problem then if you would like to provide some schema to use to run this query against along with the actual error message i'll be happy to take a look when i have time.
 
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