Use sql variable as where clause in sql - sql-server

i want to do this:
DECLARE #str varchar(max)
DECLARE #cnt bigint
set #str= 'where column=value'
set #cnt= (select count(*) from user+#str)
but the where clause is not working. getting no error but it will just ignore the where condition.

I previously suggested wrapping your last line in EXEC(), but you can't do this and return results to a variable. To do that, use the following in place of your last line:
create table #temp (theCount int)
insert into #temp EXEC('select count(*) from Photos '+#str)
set #cnt= (select top 1 theCount from #temp)
drop table #temp

Check below code, in your case condition is dynamic so you need to dynamic sql.
DECLARE #sSQL nvarchar(500);
DECLARE #ParmDefinition nvarchar(500);
DECLARE #str nvarchar(500);
set #str= 'where column=value'
SELECT #sSQL = N'SELECT #retvalOUT = COUNT(*) FROM user '+ #str +' ' ;
SET #ParmDefinition = N'#retvalOUT int OUTPUT';
EXEC sp_executesql #sSQL, #ParmDefinition, #retvalOUT=#retval OUTPUT;
SELECT #retval;

use the execute sql syntax http://technet.microsoft.com/en-us/library/ms188001.aspx
Hope this will solve your problem

Related

Dynamic SQL "Declare Scalar Variable" error

I've created the following procedure and every time I try to execute it I get the error
Must declare the scalar variable #BatchId
Essentially, all that I'm trying to do is insert the contents of a raw table into a master table with a batch id (created by a sequencer) for all inserted rows. This seemed simple enough but isn't working properly.
CREATE PROCEDURE [dbo].[usp_SessionsAppend]
#RawTable NVARCHAR(500)
AS
DECLARE #BatchId BIGINT, #SQLString NVARCHAR(MAX)
SET #BatchId = NEXT VALUE FOR [dbo].[BatchID]
SET #SQLString =
'INSERT INTO [Master].[Sessions] (
[ImportTimestamp]
,[TransactionId]
,[ParticpantId]
,[ProviderId]
,[ActivityDate]
,[Attended]
,[Minutes]
,[SurveyCompleted]
,[Instructor]
,[InstructorID]
,[ProgramCode]
,[BatchId]
)
SELECT
GETDATE() AS [ImportTimeStamp]
,NEWID() AS [TransactionId]
,[ParticpantId]
,[ProviderId]
,[ActivityDate]
,[Attended]
,[Minutes]
,[SurveyCompleted]
,[Instructor]
,[InstructorID]
,[ProgramCode]
,#BatchId
FROM' + #RawTable
EXECUTE (#SQLString)
Any help or insight would be greatly appreciated.
Use sp_executesql to pass parameters into the dynamic SQL.
eg
declare #BatchId int = NEXT VALUE FOR [dbo].[BatchID]
declare #RawTable nvarchar(200) = 'foo';
declare #SQLString nvarchar(max) =
'INSERT INTO [Master].[Sessions] (
[ImportTimestamp]
,[TransactionId]
,[ParticpantId]
,[ProviderId]
,[ActivityDate]
,[Attended]
,[Minutes]
,[SurveyCompleted]
,[Instructor]
,[InstructorID]
,[ProgramCode]
,[BatchId]
)
SELECT
GETDATE() AS [ImportTimeStamp]
,NEWID() AS [TransactionId]
,[ParticpantId]
,[ProviderId]
,[ActivityDate]
,[Attended]
,[Minutes]
,[SurveyCompleted]
,[Instructor]
,[InstructorID]
,[ProgramCode]
,#BatchId
FROM ' + quotename(#RawTable)
print #SQLString
exec sp_executesql #SQLString, N'#BatchId int', #BatchId = #BatchId;

SQL Server Is there a way to select columns from a given list

I have a list of columns that are dynamic then select the column in table that are in the list.
For example
Select (List of columns)
from tablename
Here is my code
SET NOCOUNT ON;
DECLARE #table TABLE(cols varchar(50));
DECLARE #tablename NVARCHAR(255);
DECLARE #tableid INT;
DECLARE #sSQL NVARCHAR(500);
SET #tableid = (SELECT DISTINCT TABLEID FROM faciltyShowedDetails WHERE layerid = #layerid);
SET #tablename = (SELECT dbo.FNC_Search_GetSearchTable(#tableid))
INSERT INTO #table(cols)
SELECT COLUMN_NAME
FROM faciltyShowedDetails
WHERE layerid = #layerid;
I want to select from the list of column in #table.
You would construct the query and use dynamic SQL. Assuming the "list" is really a comma-delimited list:
declare #sql nvarchar(max);
set #sql = 'select [cols] from tablename';
set #sql = replace(#sql, '[cols]', #cols);
exec sp_executesql #sql;
EDIT:
To get the columns from a table, you can use the trick:
declare #cols varchar(max);
select #cols = ', ' + columnname
from #table t;
You then have to remove the first comma (using stuff()) in the previous code.

Select data from another database in storedprocedure

I try to select data from a table of another database in my storedprocedure and the name of the other database is given by parameter. I get an error message:
'Invalid object name [#DbName].dbo.Setup'.
CREATE PROCEDURE [dbo].[spUndeliverableOrders]
#DbName sysname
AS
BEGIN
SET NOCOUNT ON;
DECLARE #Sortfield nvarchar(50)
SET #Sortfield = (SELECT COALESCE(Text, 'ToDoListeDatum') AS SortField FROM [#DbName].dbo.Setup WHERE label like 'ComboBoxSetupBatchReihenfolge')
END
GO
Can someone help me to solve this problem?
Like #ThomasSchremser said:
DECLARE #sqlquery varchar(1000)
SET #sqlquery = '(SELECT COALESCE(Text, ''ToDoListeDatum'') AS SortField FROM ['+#DbName+'].dbo.Setup WHERE label like ''ComboBoxSetupBatchReihenfolge'')'
It is upto you to decide weither you what to populate a table/variable with the results.
Either use:
insert into #table(column) exec #sqlquery...
or
sp_executesql #sqlquery...
You need to use dynamic query as below
CREATE PROCEDURE [dbo].[spUndeliverableOrders]
#DbName sysname
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
DECLARE #Str varchar(max)
CREATE TABLE #Result(Res VARCHAR(MAX))
SET #Str = 'insert into #Result SELECT TOP 1 COALESCE(Text, ''ToDoListeDatum'') AS SortField FROM ['+#DbName+'].dbo.Setup WHERE label like ''ComboBoxSetupBatchReihenfolge'''
exec(#str)
select Res from #Result
END
Modified per your script:
DECLARE #Str varchar(max)
CREATE TABLE #Result(Res VARCHAR(MAX))
SET #Str = ' SELECT TOP 1 COALESCE(Text, ''ToDoListeDatum'') AS SortField FROM ['+#DbName+'].dbo.Setup WHERE label like ''ComboBoxSetupBatchReihenfolge'''
insert into #Result
EXEC(#Str)

How can I use a local variable in SELECT FROM?

I declared a variable #Obj and assign a complete table name 'ODS..Account' to it.
DECLARE #Obj VARCHAR(255)
Then I used it in a query immediately after FROM Clause. I perceive it is just a string, unable to act as a table object. So how can I fix the code to get it works? Cheers
INSERT Control.dbo.Consistency_Check
(Table_Name
,Schema_Name
,Id
,Incremental_DateTime_Column
)
SELECT
#Tab
,'ODS'
,Id
,SystemModstamp
FROM
#Obj )
You can use a local variable as a scalar value, not as a function. To do this, you need dynamic SQL:
declare #sql varchar(max);
select #sql = '
INSERT Control.dbo.Consistency_Check(Table_Name, Schema_Name, Id, Incremental_DateTime_Column)
SELECT ''#Tab'', 'ODS', Id, SystemModstamp
FROM #Tab
';
select #sql = replace(#sql, '#tab', #tab);
exec sp_executesql #sql;
Slightly different way of doing it with dynamic SQL:
DECLARE #Obj VARCHAR(255) = 'dbo.table'
DECLARE #SQL NVARCHAR(MAX) = ''
SET #SQL = #SQL +
'INSERT Control.dbo.Consistency_Check
(Table_Name
,Schema_Name
,Id
,Incremental_DateTime_Column
)
SELECT
#Tab
,''ODS''
,Id
,SystemModstamp
FROM
' + #Obj + ''
EXEC (#SQL)
You cannot. You probably want to use dynamic query. i.e. workout the SQL query string into a variable and exec using sp_executesql.
You may use the same variable name in the dynamic SQL but I changed it to #p_Tab for the example.
DECLARE #Tab int = 3
DECLARE #SQLString nvarchar(500)
DECLARE #ParmDefinition nvarchar(500) = N'#p_Tab int';
Declare #TableName nvarchar(100) = 'ODS..Account'
/* Build the SQL string dynamicly.*/
SET #SQLString = N'INSERT Control.dbo.Consistency_Check
(Table_Name
,Schema_Name
,Id
,Incremental_DateTime_Column
)
SELECT
#p_Tab
,''ODS''
,Id
,SystemModstamp
FROM
'+ #TableName
EXECUTE sp_executesql #SQLString, #ParmDefinition,
#p_Tab = #Tab
Further reference: https://msdn.microsoft.com/en-us/library/ms188001.aspx

SQL Server variable columns name?

I am wondering why I cannot use variable column name like that:
declare #a as varchar;
set #a='TEST'
select #a from x;
Thank you
You can't do it because SQL is compiled before it knows what the value of #a is (I'm assuming in reality you would want #a to be some parameter and not hard coded like in your example).
Instead you can do this:
declare #a as varchar;
set #a='TEST'
declare #sql nvarchar(max)
set #sql = 'select [' + replace(#a, '''', '''''') + '] from x'
exec sp_executesql #sql
But be careful, this is a security vulnerability (sql-injection attacks) so shouldn't be done if you can't trust or well clean #a.
Because it is not allowed.
Insted of this you could use dynamic sql query:
declare #a as varchar;
set #a='TEST'
exec ('select ' + #a + ' from x')
Because the column names are resolved at compile time not at run time for the SQL statement.
use sp_executesql for this
Example
SET #SQLString = N'SELECT *
FROM table1
WHERE timet = #time and items in (#item)';
DECLARE #SQLString nvarchar(500);
DECLARE #ParmDefinition nvarchar(500);
SET #ParmDefinition = N'#time timestamp,
#item varchar(max) ';
EXECUTE sp_executesql
#SQLString
,#ParmDefinition
,#time = '2010-04-26 17:15:05.667'
,#item = '''Item1'',''Item2'',''Item3'',''Item4'''
;
If there are not too many columns to chose, how about a CASE WHEN statement?
DECLARE #ColName VARCHAR(50) = 'Test1'
SELECT [Foo], [Bar],
CASE
WHEN #ColName = 'Test1' THEN [Test1]
WHEN #ColName = 'Test2' THEN [Test2]
WHEN #ColName = 'Test3' THEN [Test3]
WHEN #ColName = 'Test4' THEN [Test4]
ELSE [TestDefault]
END [TestResult]
FROM [TableName];
This avoids using any EXEC.

Resources