Openquery where in clause - openquery

I am using a openquery. I tried the following syntax:
where table.column in ('''''+#parameter+''''') but still report does not work when I select multiple parameters.
Could you please help me with that?

Assuming your #Parameter is like this:
DECLARE #Parameter NVARCHAR(MAX)
SET #Parameter = 'one value'
SET #Parameter = 'first value,second value,....,last value'
First put your query statement into a variable like this:
DECLARE #TSQL NVARCHAR(MAX)
SELECT #SQL = REPLACE(N'SELECT * FROM OPENQUERY(connection, ''SELECT * FROM dbo.table WHERE table.column IN (''' + #Parameter + ''')'')', ',', ''',''')
and then execute it with
EXEC sp_ExecuteSQL #TSQL
Note: #TSQL must be NTEXT, NCHAR or NVARCHAR!!!

Related

How to use like operator in SQL query string? I got 'Incorrect syntax near 'A''

Statement:
declare #Searchkey varchar(50)='a'
declare #Sql nvarchar(max) =''
set #Sql = #Sql +
'select * from products where upper(ProductName) like %' + upper(#Searchkey) + '%'
execute sp_executesql #Sql
Error message:
Msg 102 Level 15 State 1 Line 1
Incorrect syntax near 'A'.
You do not require a dynamic query for such case, you can use below simple query to get the desired result.
declare #Searchkey varchar(50)= 'a'
select * from products where upper(ProductName) like '%' + upper(#Searchkey) + '%'
If you still want to go with Dynamic query then below are the connect syntax.
declare #Searchkey varchar(50)='a'
declare #Sql nvarchar(max) =''
set #Sql =#Sql+'select * from products where upper(ProductName) like ''%' +upper(#Searchkey)+'%'''
--print #Sql
execute sp_executesql #Sql
Note: Whenever you will get an error with a dynamic query then the best way is to print the query using print statement that will help to identify the error easily. In your case, a single quote was missing.
The reason for this error is that you need to add quotes around the search pattern, when you build the dynamic statement. But I think that your should use parameter in this dynamically built statement to prevent SQL injection issues:
DECLARE #Searchkey varchar(50) = 'a'
DECLARE #Sql nvarchar(max) = N''
SET #Sql =
#Sql +
N'SELECT * FROM products WHERE UPPER(ProductName) LIKE CONCAT(''%'', UPPER(#Searchkey), ''%'')'
PRINT #Sql
EXEC sp_executesql #Sql, N'#Searchkey varchar(50)', #Searchkey
You're not placing quotes around your search term, so the literal query that's being sent is:
select * from products where upper(ProductName) like %A%
You need to wrap the search term in quotes, like so:
set #Sql =#Sql+'select * from products where upper(ProductName) like ''%'+upper(#Searchkey)+'%'''
This will create the following query:
select * from products where upper(ProductName) like '%A%'

sp_executesql with always true condition

i have been using dynamic queries in sql-server like:
declare #sql nvarchar (1000),#condition nvarchar(100)='';
set #sql=N'select * from tablename where (0=0)'+#condition+'';
exec(#sql)
by this i was able to get my result whether the #condition has any value or not.
But i got to know that sp_executesql is better then exec as it promote query plan reuse.
So, i tried my query with `sp_executesql,
set #sql =N'select * from dbo.testclient where (0=0) #condition'
exec sp_executesql #sql,N'#condition nvarchar(100)',#condition
but it failed with an error as
Incorrect syntax near '#condition'.
My problem is how can i make the above query to work with sp_executesql where the parameter #condition can be a condition or blank (' ') and what am i doing wrong.
When you use variables such as #condition in sp_executesql, it does not simply replace your variable in the sql string with the content of the variable.
What happens is that the variable is bound to the supplied value and the sql statement is untouched.
This all means that you need to create a full sql statement which uses variables if you want to leverage query plan reuse.
For example:
SET #byIDsql = 'select * from tableName where (0=0) and Id = #Id'
SET #byNameSQL = 'select * from tableName where (0=0) and FirstName = #FirstName'
Then you can use sp_executesql to supply the value of #id and #firstName and get query plan reuse.
exec sp_executesql #byIDsql, N'#ID INT', 15
Tested code,
DECLARE #Sql nvarchar(MAX)='',
#paramlist nvarchar(4000),
#id int=3
set #paramlist = N' #id1 int'
set #Sql='select * from test where id=#id1'
exec sp_executesql #Sql,#paramlist,#id
select #Sql

How to select alias name from a table in sql server?

I have a language table and I want to select aliases from that table according to the specified language.
ALTER PROCEDURE sp_executesql
(#parameter1 NVARCHAR(MAX)
,#parameter2 NVARCHAR(MAX)
,#code NVARCHAR(MAX),#language NVARCHAR(MAX))
DECLARE #sql NVARCHAR(MAX)
SET #sql = 'SELECT '+#parameter1+' AS (SELECT #language FROM Languages WHERE code=somecolumn) '+#paramter2+' AS (SELECT #language FROM Languages WHERE code='+#code+') FROM mytable'
EDIT:
in Stored Procedure, I need something like that.
Thanks for answers..
You cannot use a subquery to build an alias in that way, you would need to use dynamic sql to do this.
DECLARE #language NVARCHAR(255) -- or whatever type your field is
SELECT #language=language FROM Languages WHERE code=#code
DECLARE #sql NVARCHAR(MAX) = 'SELECT ' + #parameter1 + ' AS ' + QUOTENAME(#language) + ' FROM MyTable'
EXEC sp_executesql #sql
(Note the inclusion of QUOTENAME around the alias - this is a safety feature in case of your alias names having invalid characters.)
You can repeat the code above for the second parameter inside your stored procedure.
Try this:
CREATE PROCEDURE sp_NameOfSP
(#parameter1 NVARCHAR(MAX)
,#parameter2 NVARCHAR(MAX)
,#code NVARCHAR(MAX)
,#language NVARCHAR(MAX))
AS
BEGIN
DECLARE #sql NVARCHAR(MAX)
SELECT TOP(1) #language=LanguageColumn FROM Languages WHERE code=somecolumn
SET #sql = 'SELECT '+#parameter1+' AS '+#language+', '
SELECT TOP(1) #language=LanguageColumn FROM Languages WHERE code=#code
SET #sql=#sql+#paramter2+' AS '+#language+' FROM mytable'
EXEC(#SQL)
END
Replace LanguageColumn with proper column name from Languages table

Get parameter from EXECUTE statement in SQL Server?

I want to create procedures with dynamic query like this
set #x = #query + CAST(#year AS varchar(10)) + ' and ' + #attribute + #operator +''''+ #value+''''
execute (#x)
Now I want to get value from execute statement but
select * from execute(#x)
does not work! Please help me
You should declare a variable you will use to get the value from the dynamic query and use executesql to execute your query.
Something like:
declare #x int
declare #sql nvarchar(max) = N'SELECT #x = SomeColumn FROM SomeTable'
exec sp_executesql #sql, N'#x int out', #x out
select #x

Stored Procedure and populating a Temp table from a linked Stored Procedure with parameters

I have a Stored Procedure (SP) in which I pass in one value. In this SP, I am trying to create/populate a Temp Table from the result of another SP that is on a Linked/remote server. That is I am trying to executute an SP in my SP and populate a temp table which my query will use.
I have tried using the following syntax, but it does not work as it seems openquery does not like the "+" or the #param1 parameter.
select * into #tempTable
from openquery([the Linked server],'exec thelinkedSPname ' + #param1)
If I have the parameter value hard coded in this it works fine.
select * into #tempTable
from openquery([the Linked server],'exec thelinkedSPname 2011')
I have also gone as far as manually building the temp table and trying to execute the linked SP but that does not work as well.
create table #tempTable(
.
.
.
)
insert into #tempTable
(
.
.
.
)
Exec [the Linked server],'exec thelinkedSPname ' + #param1
Any suggestions as to how to populate a temp table from within a SP that executes a SP via a linked server. Note the above SQL is only pseudo code
I think you are gonna need dynamic SQL, since you can't pass the parameter to an OPENQUERY like that (but first visit this link) So you would have something like this:
create table #tempTable(
.
)
DECLARE #param1 VARCHAR(10), #Query VARCHAR(8000)
SET #param1 = '2011'
SET #Query = '
SELECT *
FROM OPENQUERY([Linked Server],''exec thelinkedSPname '' + #param1+''')'
INSERT INTO #tempTable
EXEC(#Query)
With the usual disclaimers about guarding dynamic SQL, you can do this without OPENQUERY etc. Just call sp_executesql remotely:
DECLARE #sql NVARCHAR(MAX);
SET #sql = N'EXEC thelinkedSPname ' + #param1 + ';';
INSERT #temptable EXEC [LinkedServerName].database.dbo.sp_executesql #sql;
I use this method quite frequently:
DECLARE #YEAR AS VARCHAR(4) SET #YEAR = 2015
DECLARE #SQL AS VARCHAR(MAX)
DECLARE #OPENQUERY AS VARCHAR(MAX)
DECLARE #LINKEDSERVER AS VARCHAR(MAX) SET #LINKEDSERVER = 'Name of Linked Server here with out brackets'
SET #SQL='
Select
tbl1.*
FROM
dbo.Table_ON_LINKED_SERVER AS tbl1
WHERE
tbl1.number_id = ''''1''''
AND YEAR(tbl1.DATETIME) = ' + #YEAR + '
AND tbl1.NAME <> ''''%JONES%''''
'''
SET #OPENQUERY = 'SELECT * INTO ##GLOBAL_TEMP_NAME FROM OPENQUERY(['+ #LINKEDSERVER +'],''' + #SQL + ')'
--SELECT #OPENQUERY
EXEC(#OPENQUERY)
Two words: Dynamic Query.
Try this:
DECLARE #TSQL varchar(8000)
SELECT #TSQL = 'SELECT * INTO #tempTable FROM OPENQUERY([the Linked server],''exec [the Linked server].DBName.dbo.thelinkedSPname ' + #param1 + ''')'
EXEC (#TSQL)
This is well documented here:
How to pass a variable to a linked server query
With some care you could use a shared temp table:
DECLARE #Qry AS VARCHAR(MAX)
SET #Qry = 'select * into ##tempTable from openquery([the Linked server],''exec thelinkedSPname ' + #param1 + ''')'
EXEC (#Qry)
-- Now just use the shared Temp table, or I suppose you could copy it to a temp table just as you wanted it:
SELECT * INTO #tempTable FROM( SELECT * FROM ##tempTable)tbl
DROP TABLE ##tempTable

Resources