I am trying to execute this conditional statement from a string, but I always get errors.
Is there a way to CAST or CONVERT this varchar to a logical string?
I am using SQL Server 2000
Declare #myQuery varchar(100)
SET #myQuery= '3043=3043 OR ( 3043=97 AND 0=8065 ) OR 3043=1853 OR 3043=5749'
if(#myQuery)
select 'ok'
I want to execute this:
These conditions need to go in a where clause so they are properly interpreted. Something like:
declare #myquery varchar(100)
set #myquery = '3043 = 3043 or (3043 = 97 and 0=8065) or 3043 = 1853 or 3043 = 5749'
exec('select ''ok'' where ' + #myquery)
If you want to use it in IF condition, you need to set the flag using sp_executesql as below:
Declare #myQuery nvarchar(100)
Declare #flag tinyint
SET #myQuery= 'select #flag = 1 where 3043=3043 OR ( 3043=97 AND 0=8065 ) OR 3043=1853 OR 3043=5749'
exec sp_executesql #myQuery, N'#flag tinyint output', #flag = #flag output
if(#flag = 1)
select 'ok'
Related
I have an expression:
DECLARE #Conditions NVARCHAR(MAX) = '200>100 AND YEAR(GETDATE())=2022'
I want to check if the expression is true.
To execute a string as a SQL statement from within T-SQL, use sp_executesql
In your case you'd want to make use of output parameters and embed your code snippet in a larger statement such as SELECT #outputParam = CASE WHEN <your code snippet> THEN 1 ELSE 0 END (As T-SQL doesn't have a boolean data type.)
DECLARE #Conditions NVARCHAR(MAX) = '200>100 AND YEAR(GETDATE())=2022';
DECLARE #SQLString NVARCHAR(MAX);
DECLARE #SQLResult INT;
SET #SQLString = CONCAT(
N'SELECT #Result = CASE WHEN ',
#Conditions,
N' THEN 1 ELSE 0 END;'
)
EXECUTE sp_executesql
#SQLString
,N'#Result INT OUTPUT'
,#Result = #SQLResult OUTPUT;
-- This SELECT statement returns the value of the OUTPUT parameter.
SELECT #SQLResult;
https://dbfiddle.uk/?rdbms=sqlserver_2019&fiddle=5697ea4d14201e44d0e8888abbc6037b
EDIT:
Avoiding CASE expressions by initialising the result to 0 (fail) and only setting it to 1 (success) if the conditions are true.
DECLARE #Conditions NVARCHAR(MAX) = '200>100 AND YEAR(GETDATE())=2022';
DECLARE #SQLString NVARCHAR(MAX);
DECLARE #SQLResult INT = 0;
SET #SQLString = CONCAT(
N'SELECT #Result = 1 WHERE ',
#Conditions
)
EXECUTE sp_executesql
#SQLString
,N'#Result INT OUTPUT'
,#Result = #SQLResult OUTPUT;
-- This SELECT statement returns the value of the OUTPUT parameter.
SELECT #SQLResult;
https://dbfiddle.uk/?rdbms=sqlserver_2019&fiddle=3e375c464f1eab2e652bc446a4c7484f
DECLARE #GET DATETIME
SET #GET= GETDATE()
DECLARE #Val VARCHAR(10)
SET #Val='wk'
--SELECT DATEADD(#Type,2,#GET)
SELECT DATEPART(wk,GETDATE()) -- WORKING
The above line works but when i pass it as a paramter it doesn't work.
SELECT DATEPART(#val,GETDATE()) -- NOT WORKING
The interval passed seems to be of other data type.
Make it as Dynamic Query
DECLARE #sql nvarchar(500)
DECLARE #Val VARCHAR(10)
SET #Val='week' --Quarter, Month
set #sql = 'SELECT DATEPART('+#val+',GETDATE())'
exec sp_executesql #sql
Or Alternatively you can use this
If #val = 'Week'
SELECT DATEPART(Week,GETDATE())
Else If #val = 'Month'
SELECT DATEPART(Month,GETDATE())
....
This question already has an answer here:
Creating SumIf function in SQL Server 2012
(1 answer)
Closed 7 years ago.
I have the following sql function, but not running correctly, the intended returned value is the total
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
Create FUNCTION [dbo].[SumIf](#ColumnName [varchar](100), #Criteria [varchar](500))
RETURNS [decimal] AS
BEGIN
-- Declare the return variable here
DECLARE #Total Decimal
DECLARE #TableName Decimal
Select #Total = SUM(#ColumnName) from #TableName where #Criteria
RETURN #Total
END
the use syntax would be something like
Select dbo.sumif(fees.fee_amount, Fees.Fee_Code ='B01')
So the tablename would also need to be extracted from the columnname variable passed.
I don't think you will be able to implement your function that way. You're essentially trying to pass an expression to the function which I don't think is possible in SQL Server. You may be able to do it with dynamic SQL passing in strings but not as cleanly as you're hoping.
you need dynamic SQL to do this, but unfortunately you can't use dynamic SQL inside a UDF. try this-
DECLARE #ColumnName [nvarchar](100) = '' --fill in values here
DECLARE #TableName [nvarchar](100) = ''
DECLARE #Criteria [nvarchar](500) = ''
DECLARE #s nvarchar(max)
DECLARE #res bigint
set #s = 'SELECT #result = SUM(' + #ColumnName + ') from ' + #TableName + ' where ' + #Criteria
exec sp_executesql #s, N'#result OUTPUT', #result = #res OUTPUT
select #res
You are way on the wrong track. If you wanted to put sumif() in a select statement, it would need to be a user-defined aggregation function, rather than just a user-defined function. The fact that you've declared #TableName to be decimal and then use it in a from clause points to other issues.
So, my suggestion is that you just do this in-line:
select sum(case when <condition> then <columnname> else 0 end) as sumval
from <tablename>
If you wanted a programming block to put the data together, then use a stored procedure. Something like:
Create FUNCTION [dbo].SumIf(#ColumnName varchar(100),
#TableName varchar(255)
#Criteria varchar(500),
#Total Decimal OUTPUT)
) AS
BEGIN
DECLARE #sql nvarchar(max) = 'Select #Total = SUM(#ColumnName) from #TableName where #Criteria';
set #sql = replace(#sql, '#ColumnName', #ColumnName);
set #sql = replace(#sql, '#TableName', #TableName);
set #sql = replace(#sql, '#Criteria', #Criteria);
sp_execute_sql #sql, N'#total decimal output', #total = #total output;
END;
I have this requirement to be implemented in a stored procedure. Dynamically query the database to get the count of a table, store it in a t-sql variable and then take some decisions based on that.
This is the stored procedure that i am working on . This is throwing some errors as i don't think there is a simple way of assigning the result of a tsql dynamic query to a variable.
CREATE PROCEDURE test
AS
BEGIN
DECLARE #sql VARCHAR(255)
DECLARE #cnt int
SET #sql = 'SELECT COUNT(1) FROM myTable'
SET #cnt = EXEC(#sql)
IF (#cnt > 0)
PRINT 'A'
ELSE
PRINT 'B'
END
GO
Could someone tell me if there is a simpler way of achieving this using T-SQL ?
Thanks.
alternative:
declare #tablename varchar(512) = 'sometable'
declare #sql nvarchar(512) = 'set #count = (select count(*) from ' + #tablename + ')'
declare #count int
execute sp_executesql #sql, N'#count int output', #count=#count output
select case when #count > 0 then 'A' else 'B' end
Try this:
SET #sql = 'SELECT #cnt = COUNT(1) FROM myTable'
EXEC(#sql)
my sql statement is something like this below
DECLARE #OLD_NAV_VALUE AS INT
DECLARE #FINAL AS INT
SELECT #OLD_NAV_VALUE = [col1] from TBL_BA where DATE = #id_Date
SET #FINAL = #OLD_NAV_VALUE * 50
But the problem i am haveing here is that the column name in the select statement which is given as [col1] is a dynamic value. So i am trying something like this below.
DECLARE #OLD_NAV_VALUE AS INT
DECLARE #FINAL AS INT
EXEC('SELECT #OLD_NAV_VALUE = [' + #DYNAMIC_COL_NAME + '] from TBL_BA where DATE = ' + #id_Date)
SET #FINAL = #OLD_NAV_VALUE * 50
this gives an error that #OLD_NAV_VALUE has to be declared. So i tried declaring #OLD_NAV_VALUE inside the EXEC statement. But if i do this i am not able to use the same outside the EXEC statement.
Please let me know how to do this.
You can also use the sp_executesql statement with an output parameter:
declare #field nvarchar(50);
set #field = N'FieldToSelect';
declare #sql nvarchar(3000);
declare #parmDefinition nvarchar(500);
SET #parmDefinition = N'#returnValueOUT nvarchar(50) OUTPUT';
set #sql = N'SELECT #ReturnValueOUT = ' + #Field + ' FROM [TableName] WHERE [SomeCondition]'
declare #returnValue nvarchar(50);
EXECUTE sp_executesql #sql, #parmDefinition, #returnValueOut = #returnValue OUTPUT;
SELECT #returnValue
First, I'd suggest that you do a Google on "Erland dynamic SQL" and read his white paper on the subject.
Your design is probably not the best if it requires that you use a dynamic column name like this.
The reason that you can't do what you're trying to do is that everything in the EXEC is entirely in its own scope. If you absolutely have to do it this way though then you could use a table (either a normal table, or a global temporary table) to store the value for use outside of the EXEC.
We've used sp_executesql. Here's another example of a parameterized record count:
DECLARE #sql AS nvarchar(MAX)
SET #sql = N'SELECT #RecordCount = COUNT(*) FROM [{#SchemaName}].[{#TableName}]'
SET #sql = REPLACE(#sql, '{#SchemaName}', #SchemaName)
SET #sql = REPLACE(#sql, '{#TableName}', #TableName)
DECLARE #RecordCount AS int
EXEC sp_executesql
#query = #sql,
#params = N'#RecordCount INT OUTPUT',
#RecordCount = #RecordCount OUTPUT
This worked for me.
I declared a temp table and used it to receive the values from the select statement.
Something like below.
declare #i int
declare #v int
create table #t (val int)
insert into #t
exec ('declare #i int set #i = 0 select #i+1')
select * from #t