using dynamic IN clause in MSSQL - sql

Why the following SQL does not fetch me anything
DECLARE #Status AS VARCHAR(400)
SET #status = '''Closed'',''OPEN'''
select * from MYTABLE where status in(#status)
While as
select * from MYTABLE where status in('Closed','Open') fetches me rows

You can if you want do some dynamic SQL but I think it is not really competitive..
DECLARE #Status nVARCHAR(400),
#SQL nvarchar(500)
SET #status = '''Closed'''+','+'''OPEN'''
set #SQL = '
select * from [MYTABLE] where status in('+#status +')'
exec sp_executesql #SQL
GO

Your first question checks if the value 'Closed','OPEN' exists in the database. The values is not expanded.
If you use SQL Server 2008 or later you can use Table Valued Parameters to achieve the same thing.

Related

sql server select rows into string

I have the following query.
declare #column_names varchar(1000)
declare #result varchar(1000)
set #column_names='id,firstname,lastname,age,city,country'
set #result=''
select #result=#result+#column_names +','+from studenttable where id='1'
But this query returns id,firstname,lastname,age,city,country as result
and not like 1,john,j,21,newyork,us.
How to change query so that #result will contain actual entries in comma-separated form?
Please reply. Thanks.
To execute dynamic T-SQL statements use sp_executesql as:
EXECUTE sp_executesql
N'SELECT ' +#column_names +' FROM studenttable
WHERE id= #id',
N'#id tinyint',
#id= 1;

sql stored procedure single quotes

I have a stored procedure as below
create procedure TestTry
BEGIN
declare #query varchar(max)
SET NOCOUNT ON;
set #query = 'select * from table1 when RECORD_FLAG <> 't'
then Convert(Decimal(10,4),ISNULL(T.HISTORY_PCR ,0)) else '0'';
exec (#query)
end
Here after RECORD_FLAG <> I want to give it in single quotes and also give 0 in single quotes how to give that
The above shown is a sample in real time my query is big I have to give the query in #query only
Use '' (double) for ' (single)
set #query = 'select * from table1 when RECORD_FLAG <> ''t''
then Convert(Decimal(10,4),ISNULL(T.HISTORY_PCR ,0)) else ''0''';
create procedure TestTry
AS --<-- you'er also missing AS key word here
BEGIN
SET NOCOUNT ON;
declare #query varchar(max)
set #query = 'select * from table1 when RECORD_FLAG <> ''t''
then Convert(Decimal(10,4),ISNULL(T.HISTORY_PCR ,0)) else ''0''';
EXECUTE sp_executesql #query --<-- use this syntax to execute dynamic sql
end
Also you do not need to use dynamic sql for such a simple query,
dynamic sql is the devil of sql and you want to avoid using it
whenever possible.
Your Query
Also your query syntax isnt right you are trying to execute a query as follows
select *
from table1
when RECORD_FLAG <> 't' --<-- cant use WHEN without the CASE statement also you
--cannot use a Case statement here right after your table name

Selecting a database from a variable

So I have two databases that have no relationship between them. The first one is where my dbo.Clients exists and has a column of the database name of the second db . My thought was to select the dbName from the Clients then use that variable to select data from the second database.
The query doesnt run can some one shed a little light? Thanks.
#dbName varchar(50) OUTPUT,
#clientID varchar(50)
AS
BEGIN
SET NOCOUNT ON;
-- Insert statements for procedure here
SELECT * FROM sql02.iproconfig4.dbo.Clients
SET #dbName = (SELECT Clients.ClientDatabase FROM sql02.iproconfig4.dbo.Clients WHERE ClientID = #clientID)
SELECT * FROM sql02.#dbName.dbo.Discovery
END
You will need to use dynamic SQL to accomplish this:
DECLARE #sql nvarchar(max)
SET #sql = 'SELECT * FROM sql02.' + #dbName + '.dbo.Discovery'
EXEC sp_executesql #sql

Run SQL pre-defined function stored in table

I have a table which stores a SQL predefined function, like CONVERT(VARCHAR(10), '2012-08-21 00:16:41.993', 101) in a row/column. While retrieving the result from table, it should run the function and give the final outcome as "2012-08-21", instead right now it returns the same function statement. I am running select (select RunDate from RunDate) and using SQL server database.
Kindly help!!
You need to use dynamic SQL for this. You can't just nest expressions and have SQL evaluate the output...
DECLARE #x TABLE(sql NVARCHAR(255));
INSERT #x(sql) SELECT N'CONVERT(VARCHAR(10), ''2012-08-21 00:16:41.993'', 101)';
DECLARE #sql NVARCHAR(MAX);
SELECT #sql = N'SELECT ' + sql FROM #x;
EXEC sp_executesql #sql;
It would look like this (adjust accordingly):
DECLARE #predef VARCHAR(1000);
DECLARE #sqlquery VARCHAR(1000);
SELECT #predef = (SELECT top 1 Value FROM Parameters Where Name = 'MYFUNC');
SET #sqlquery = 'select ' + #predef + ' from SomeTable';
EXECUTE ( #sqlquery );
One tip: here be dragons. Beware of SQL Injection.

SQL Table selection

I'm trying to create some means of dynamically selecting the table for a procedure to run on based on an ID sent to the database. Something like :
#TableId int
As
Declare #nameoftable varchar(50)
select #nameoftable = Nameoftable from tablelist where id = #tableid
-- returning on selected table
Select somestuff
from #nameoftable
Any ideas?
You need to use dynamic SQL
#TableId int
As
Declare #nameoftable varchar(50)
select #nameoftable = Nameoftable from tablelist where id = #tableid
-- returning on selected table
declare #sql nvarchar(1000)
set #sql = 'Select somestuff from ' + Quotename(#nameoftable)
exec(#sql)
In MS SQL Server you can use sp_executesql to execute dynamic queries. Read The Curse and Blessings of Dynamic SQL, it helped me alot.