creating dynamic query in variable - sql-server

I am creating a dynamic query in sql server 2005 stored procedure and I am getting error if
dates are sent empty/null to the stored procedure that:
This input parameter cannot be converted
So, how to check in Stored procedure that covert only id date is not empty:
below is my query. I have checked the null in if condition but then also it is showing me error
If #startDate IS NOT NULL AND #endDate is Not null
Begin
set #strCondition = ' FO.Rf_Date >= convert(datetime, ''' + Convert(varchar,#startDate,112) + ''') and FO.Rf_Date<= convert(datetime, ''' + Convert(varchar,#endDate,112) + ''')'
End

If they can be empty or null you need to also exclude the empty variables, E.g.
IF NULLIF(#startDate, '') IS NOT NULL AND NULLIF(#endDate, '') IS NOT NULL

You can also make use of ISDATE() Function along with CASE statement something like this..
SET #strCondition = N' SELECT * FROM TableName WHERE 1 = 1 ' --<-- 1 = 1 so you can append any more line starting with 'AND'
+ CASE WHEN ISDATE(NULLIF(#startDate,'')) = 1
THEN N' AND FO.Rf_Date >= convert(datetime, ''' + Convert(varchar,#startDate,112) + ''') '
ELSE N'' END
+ CASE WHEN ISDATE(NULLIF(#endDate,'')) = 1
THEN N' AND FO.Rf_Date <= convert(datetime, ''' + Convert(varchar,#endDate,112) + ''')'
ELSE N'' END
Note
ISDATE() function returns 0 if the passed parameter isnt date value, It also returns 0 is the passed value is NULL.

Related

where clause not working for varchar field as expected in SQL stored procedure

I have a stored procedure(working dynamically) which accepts many parameters and one such parameter is #lAmountValue which is filter out the records based on the field Min. I have used the below where clause to filter out the records based on the value of Min. But it is retrieving records incorrectly where it is fetching the null values, empty strings along with my criteria and also values greater than the specified value(when searching with EqualTo criteria). The same filter is working correctly for numeric fields but not for varchar fields. Min is a varchar field and the column values in the table can contain Null, empty strings, numbers and strings. Please help to find out the error in my where clause.
if #lComparer = 'EqualTo'
Set #Query= #Query +'and TN.Min is not null and TN.Min !='' and cast(TN.Min as varchar(30)) = '''' + CAST(#lAmountValue as varchar(30)) + '''' '
else if #lComparer = 'GreaterThan'
Set #Query= #Query +'and TN.Min is not null and TN.Min !='' and cast(TN.Min as varchar(30)) > '''' + CAST(#lAmountValue as varchar(30)) + '''' '
else if #lComparer = 'LessThan'
Set #Query= #Query +'and TN.Min is not null and TN.Min !='' and cast(TN.Min as varchar(30)) < '''' + CAST(#lAmountValue as varchar(30)) + '''' '

T-SQL openquery doesn't update on NULL value

I have a Microsoft SQL Server trigger that updates a remote database with new values when the local database is updated. Everything works fine, and I tested the script and it updates fine, unless there is a null value.
The code is below:
DECLARE #TSQL nvarchar(4000);
SELECT #TSQL =
'UPDATE
OPENQUERY(TEST,''SELECT * FROM test_db WHERE id = ' + convert(VARCHAR(MAX), #id) +''')
SET
parent_id = ' + convert(VARCHAR(MAX), #parent_id) + ', user_id = ' + convert(VARCHAR(MAX), #user_id) + ', item_id = ' + convert(VARCHAR(MAX), #item_id) + ''
EXEC (#TSQL)
Everything works well if all the fields have values, but if one column is null, then the query doesn't update the row at all, no errors thrown. I tried to use COALESCE() to change the null variables to empty strings, and it will then update the row, but all the null columns become 0's and I want them to stay as NULL values. All the columns in both database allow null values and default to null so I'm not sure why I cannot update the database.
Any help would be nice, thanks!
Try this. Use ISNULL and if the value is null, use 'NULL' in single quotes. When the string is concatenated together, it won't keep the quotes, so it would set it to a NULL value and not a string of 'NULL'.
DECLARE #TSQL nvarchar(4000);
SELECT #TSQL =
'UPDATE
OPENQUERY(TEST,''SELECT * FROM test_db WHERE id = ' + convert(VARCHAR(MAX), #id) +''')
SET
parent_id = ' + ISNULL(convert(VARCHAR(MAX), #parent_id), 'NULL') + ',
user_id = ' + ISNULL(convert(VARCHAR(MAX), #user_id), 'NULL') + ',
item_id = ' + ISNULL(convert(VARCHAR(MAX), #item_id), 'NULL') + ''
EXEC (#TSQL)

Run a stored procedure with all the variable in declare and retrieving no values

I've managed to write my stored procedure, it is running now but no results are retrieved.
CREATE PROCEDURE [dbo].[SigleEnseigne]
AS
BEGIN
DECLARE #Sigle VARCHAR(150),
#Enseigne VARCHAR(150),
#SigleEnseigne1 VARCHAR(150)
SELECT #Sigle = ISNULL(John_Jack.Sigle, '') ,
#Enseigne = ISNULL(John_Jack.Enseigne, '') ,
#SigleEnseigne1 = CASE WHEN Code_Juridique LIKE 'M%'
THEN ' / '
+ ISNULL(John_Jack.Enseigne, '')
WHEN ISNULL(John_Jack.Sigle, '') = ''
AND ISNULL(John_Jack.Enseigne, '') = ''
THEN ''
ELSE #Sigle + ' / ' + #Enseigne
END
FROM John_Jack
SELECT #Sigle, #Enseigne, #SigleEnseigne1
END
Yet when I'm running SELECT * FROM John_Jack, I do have results.
What I'm doing wrong?
Have I misunderstood something along the way?
I've' checked on the internet but nothing relevant stood out.
It looks like you're missing some condition in your select here:
SELECT #Sigle = ...
FROM John_Jack
thus in the case when it is more then one record in John_Jack table, your variables assignment will not work as intended: you can't put multiple values from table into variable.
you have either write some filtering condition in where clause, or (if you don't care what exactly values you'll get from table) just use something like
SELECT TOP 1
#Sigle = ...
FROM John_Jack
Or, if you need to retrieve whole table data "reformatted" according to your logic (as you stated in comments) - then just get rid of these variables and rewrite your procedure as
CREATE PROCEDURE [dbo].[SigleEnseigne]
AS
BEGIN
SELECT
ISNULL(John_Jack.Sigle, '') as Sigle,
ISNULL(John_Jack.Enseigne, '') as Enseigne,
CASE WHEN Code_Juridique LIKE 'M%'
THEN ' / '
+ ISNULL(John_Jack.Enseigne, '')
WHEN ISNULL(John_Jack.Sigle, '') = ''
AND ISNULL(John_Jack.Enseigne, '') = ''
THEN ''
ELSE ISNULL(John_Jack.Sigle, '')
+ ' / ' + ISNULL(John_Jack.Enseigne, '')
END as SigleEnseigne1
FROM John_Jack
END

Need help in dynamic procedure

I have a start date and end date so how to use both in place of getdate()
I have a code in which if the date interval between start and end date is less than 30 than it should show the start and end date. Instead it is showing error-
Explicit conversion from data type int to date is not allowed.
I am notusing int anywhere but still it is showing I have tried convert in argument passing and other things but its not stopping showing error.
My code is-
if object_id('ias_test_SCHEMA.week2','p') is not null
drop procedure ias_test_SCHEMA.week2;
go
create procedure ias_test_SCHEMA.week2(#startdate date,#enddate date)
as
BEGIN
declare #datediff integer,
#res varchar(30);
set #datediff = DATEDIFF(day, #startdate, #enddate);
if #datediff<=30
begin
declare #stmt nvarchar(max),
#stmt1 nvarchar(max);
set #stmt= N'SELECT #res=(DATENAME(DAY,convert(date,'+convert(nvarchar(20),#startdate)+')) + '' '' + DATENAME(MONTH,convert(date,'+convert(nvarchar(20),#startdate)+')) + '' '' + DATENAME(YEAR,convert(date,'+convert(nvarchar(20),#startdate)+')))';
Execute sp_executesql #stmt, N'#res varchar output',
#res=#res output;
print 'The date is:' + #res;
set #stmt1= N'SELECT DATENAME(DAY,convert(date,'+convert(nvarchar(20),#enddate)+')) + '' '' + DATENAME(MONTH,convert(date,'+convert(nvarchar(20),#enddate)+')) + '' '' + DATENAME(YEAR,convert(date,'+convert(nvarchar(20),#enddate)+'))';
Execute sp_executesql #stmt1;
end;
end;
go
and I am executing it by line-
execute ias_test_SCHEMA.week2 '2015-10-03','2015-10-08';
but it is showing compiled successfully but at the time of result is not showing error. I am stuck here!
Please can anyone help me through it? Thank you!
these are the commands produced by your code:
SELECT #res=(DATENAME(DAY,convert(date,2015-10-03)) + ' ' + DATENAME(MONTH,convert(date,2015-10-03)) + ' ' + DATENAME(YEAR,convert(date,2015-10-03)))
SELECT DATENAME(DAY,convert(date,2015-10-08)) + ' ' + DATENAME(MONTH,convert(date,2015-10-08)) + ' ' + DATENAME(YEAR,convert(date,2015-10-08))
the issue is in the missing quotes around the dates inside the convert built in the dynamic string.
if you run:
select convert(date,2015-10-03);
you get:
Msg 529, Level 16, State 2, Line 1 Explicit conversion from data type
int to date is not allowed.
the following command can be executed successfully:
select convert(date,'2015-10-03');
the solution is to add escaped single quotes when building the dynamic query:
set #stmt= N'SELECT #res=(DATENAME(DAY,convert(date,'''+convert(nvarchar(20),#startdate)+''')) + '' '' + DATENAME(MONTH,convert(date,'''+convert(nvarchar(20),#startdate)+''')) + '' '' + DATENAME(YEAR,convert(date,'''+convert(nvarchar(20),#startdate)+''')))';

ISNULL() On Value, But If Not Null, Put Quotes

I am building dynamic SQL statements. I am checking for null values, and if the value is not null, putting single quotes around the parameter value. In the below #TEST_GU is a string parameter.
BEGIN TRAN
DECLARE #SQL nvarchar(max)
SELECT #SQL = 'UPDATE [THIS IS A TABLE]
SET [TEST_GU]=' + '''' + ISNULL(#TEST_GU,'') + ''''+',
+ ' SELECT [TEST_GU] FROM
[THIS IS A TABLE]
WHERE [TEST_GU] =' + '''' + ISNULL(#TEST_GU,'') + '''' +''
PRINT LEN(#SQL)
EXEC (#SQL)
COMMIT
This wont work because if its null, it ends up putting quotes around the empty value, so makes the whole statement become unformatted. So my question is, in the above format, is it possible to check for null values, if null use the second argument of the ISNULL method (in this case, an empty ''). If it is not null, put the parameter value in single quotes.
Just put the quotes inside the isnull():
SELECT #SQL = 'UPDATE [THIS IS A TABLE]
SET [TEST_GU]=' + '''' + ISNULL(''''+#TEST_GU+'''','') + ''''+',
+ ' SELECT [TEST_GU] FROM
[THIS IS A TABLE]
The concatenation will return NULL if the value is NULL, so it still does what you want.

Resources