Passing Multiple Parameters to SQL Server [duplicate] - sql

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Parameterizing an SQL IN clause?
Comma-separated value insertion In SQL Server 2005
I'm trying to search in my database using where in clause, but my string is in follow format:
'233052,57516351,254689'
I need to do an consult in my database using the following query:
SELECT * FROM myTable WHERE field IN (#list_string)
How I do to make this action?

Use Table-valued parameters, introduced in SQL Server 2008.
These let you pass in a table structure that you can use to query on.
For other options, I suggest reading Arrays and Lists in SQL Server, by Erland Sommarskog.

I've been using Itai Goldstein's Split function for years for this very situation. You could then do the following:
SELECT *
FROM [myTable]
WHERE [field] IN (
SELECT [Data]
FROM [dbo].[Split] (#list_string, ',')
);

Try EXEC of sql statement concatenation:
declare #sql varchar(200)
set #sql='SELECT * FROM myTable WHERE field IN ('+#list_string+')'
exec(#sql)

Related

Passing query string through variable value fails [duplicate]

This question already has answers here:
Use dynamic table name in sql server query
(2 answers)
Closed 7 months ago.
Using Microsoft SQL Server 2015
This works
create procedure Checking1(#SQLQueryString nvarchar(max))
as
begin
select * from MyTable
end
This is not working
create procedure Checking1(#SQLQueryString nvarchar(max))
as
begin
#SQLQueryString
end;
What am I doing wrong?
You need to tell SQL Server to execute your dynamic-SQL
https://learn.microsoft.com/en-us/sql/relational-databases/system-stored-procedures/sp-executesql-transact-sql?view=sql-server-ver16
or
https://www.mssqltips.com/sqlservertip/1160/execute-dynamic-sql-commands-in-sql-server/

Run SQL Dynamic using column value [duplicate]

This question already has answers here:
T-SQL: How to use parameters in dynamic SQL?
(4 answers)
sql stored procedure argument as parameter for dynamic query
(2 answers)
SQL Server 2017 - How to pass a parameter in a SELECT inside a dynamic SQL
(1 answer)
Closed last year.
I am using dynamic SQL.
I inserted a select statement into one row from #example, I want to call that select statement and run it with dynamic SQL, my select stored has a variable call #NumOrder
create table #example(id int, description varchar(1000))
insert into #example(id, description)
values(1, 'select case when name=''Carlos'' then ''Pass'' else ''FAIL'' from server.dbo.person where number = #NumOrder')
declare #NumOrder int, #SQL nvarchar(max)
set #NumOrder=2621
set #SQL='description'
--here is where I want to call my query and is failing
--once I filled #NumOrder I want to display the results
exec(#SQL)
I want to run this dynamic SQL using a row stored into the temp table, I know that I can put the complete select statement into the #SQL and works but I want to know if there is a way to call the select statement in a row stored from a table. Is there a way to do this?

SQL Query for paramaterized dynamic table

One of the product teams I manage has an abundance of queries that use dynamic sql queries injecting the table in using concatenation. While it has sanitisation, I am trying to completely remove dynamic sql.
Is there a way to parameterise the table name?
I am trying to think of how I can query a table something like:
SELECT * FROM (SELECT DISTINCT Table_Name FROM INFORMATION_SCHEMA.Tables WHERE Table_Name = :queryParam)
Is this possible?
There is no way to "properly" prevent SQL injection completely from within SQL, the calling application layer should do this prior to executing any SQL statement.
Solve the problem by using an ORM or building the code to protect yourself from SQL injection when you generate the SQL in the application code.
This feels like a classic XY problem, try to take a step back and consider that you need to protect the access to the SQL server itself rather than sanitise everything from within "after" your SQL server has been accessed.
I am trying to completely remove dynamic sql.
You can't do it without Dynamic SQL.
Is this possible?
No, it's not possible, you cannot parameterize identifiers in SQL queries.
Why?
From the Books online page for Variables, Variables can be used only in expressions, not in place of object names or keywords. To construct dynamic SQL statements, use EXECUTE.
This is the only way to do it:
DECLARE #Column SysName = N'Table_Name',
#Param NVARCHAR(128) = N'ParamValue';
DECLARE #SQL NVARCHAR(MAX)=N'SELECT *
FROM(
SELECT '+ QUOTENAME(#Column) +
'FROM INFORMATION_SCHEMA.Tables
WHERE ' + QUOTENAME(#Column) + ' = #Param
) T';
EXECUTE sp_executesql #SQl,
N'#Param NVARCHAR(128)',
#Param;

Creating a SQL Use statement for cross server query [duplicate]

This question already has answers here:
Set database name dynamically in SQL Server stored procedure?
(3 answers)
Closed 9 years ago.
How do you create a cross server query use statement to run a select. This is what I have but I cant seem to get anything than 'does not exist'
Thanks!
DECLARE #ServerVar AS NVARCHAR (MAX)
SET #ServerVar = 'servera/server1';
DECLARE #DBVar AS NVARCHAR (MAX)
SET #DBVar = 'db';
Declare #reportVar nvarchar(max);
Set #reportVar = 'USE ' + quotename(#ServerVar) + '.' + quotename(#DBVar);
EXEC (#reportVar);
SELECT * FROM myTable;
You need to link the remote server to your local one. After that you can query remote server from your local one even without using Use command
This is a good time to use a Linked Server and possibly even synonyms and dynamic sql.
See similar post: Set database name dynamically in SQL Server stored procedure?

Dynamically creating the IN clause in a stored procedure [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Need help in dynamic query with IN Clause
I am using SQL server 2008 and this is the problem that I am facing. I have a table named Cars with a column Company. Now I have a stored procedure that looks something like this
CREATE PROCEDURE FindCars (#CompanyNames varchar(500))
AS
SELECT * FROM Cars WHERE Company IN (#CompanyNames)
I tried something like this and failed
DECLARE #CompanyNames varchar(500)
SET #CompanyNames = '''Ford'',''BMW'''
exec FindCars #CompanyNames
I dont get any rows returned. When I do the following
DECLARE #CompanyNames varchar(500)
SET #CompanyNames = '''Ford'',''BMW'''
Select #CompanyNames
I get the following result
'Ford','BMW'
and if I replace this value in the select statement inside the stored procedure, it works
SELECT * FROM Cars where Company in ('Ford','BMW')
Thus I think that the stored procedure seems to be treating 'Ford','BMW' as one string rather than an array. Could someone please help me with this. How do I dynamically construct the string/array required in the IN clause of the select statement inside the stored procedure.
You are right, you created one string, and that is being processed as a list of strings that contains one string. The commas are just characters in that one string. The only equivilent to an array in SQL Server is a table.
For example; WHERE x IN (SELECT y FROM z).
For this reason many people create a SPLIT_STRING() function that returns a table of items from a given comma delimitted string...
WHERE x IN (SELECT item FROM dbo.split_string(#input_string))
There are many ways to implement that split string. Some return strings, some cast to integers, some accept a second "delimiter" parameter, etc, etc. You can search the internet for SQL SERVER SPLIT STRING and get many results - Including here in StackOverflow.
An alternative is to use dynamic SQL; SQL that writes SQL.
SET #sql = 'SELECT * FROM x WHERE y IN (' + #input_string_list + ')'
SP_EXECEUTESQL #sql
(I recommend SP_EXECUTESQL over just EXEC because the former allows you to use parameterised queries, but the latter does not.)