SQL stored procedure variable null checking - sql

Below is part of a stored procedure that I have, it would be of great help if you can point me why is that even when #DefaultID is null after executing the select statement it does not enter the if condition, is there are different method I have to follow to assign the value to #DefaultID for it to be available for null checking.
Thank you in advance.
DECLARE #DefaultID varchar(25)
DECLARE #ISDefault varchar(1)
SELECT #DefaultID = (SELECT TABLE1.DEFID as DEFID
FROM TABLE1
WHERE TABLE1.ID = '123')
IF (#DefaultID = '')
SET #ISDefault = '1'
ELSE
SET #ISDefault = '0'

Use
IF #DefaultID IS NULL
Instead of IF #DefaultID =''
NULL and '' are two different things.

simply use this :-
IF(#DefaultID is NULL)

Please check using
IF ISNULL(#DefaultID, '') = '' instead of IF(#DefaultID = '')
I guess you are using MS Sql server.

IF(len(#DefaultID) > 0)
SET #ISDefault = '1'
ELSE
SET #ISDefault = '0'

Related

Use variable sql for column name

Before you shout at me in CAPS for not searching - I have! Dynamic SQL is good, dynamic SQL is bad. Learning a lot..
I can accomplish what I'm after by using logic in there WHERE clause, but it adds a significant amount of run time. The query takes 8 seconds if I hard code the criteria and 1:20 if I use the WHERE logic.
Here is what I'd like to do:
Declare #EmployeeToggle varchar(30)
Declare #Employee_ID varchar(30)
Declare #EmployeeField varchar(100)
set #EmployeeToggle = '1'
set #Employee_ID = '1166'
set #EmployeeField = case when #EmployeeToggle = '1' then 'Field1' else
'Field2' end;
select * from Table1 where #EmployeeField = #Employee_ID
I don't think it's possible without dynamic sql. I still don't know whether or not I should use it. It's my thought that it would take the query back down to 8 seconds, because it would immediately know which field to use in the where clause.
Alternatively, a few ways to do it in the where only:
where (( not #EmployeeToggle = '1') or Field1 = #Employee_ID) and
(#EmployeeToggle = '1' or Field2 = #Employee_ID)
where (1=(case when #EmployeeToggle = '1' then 1 else 0 end ) or Field1 =
#Employee_ID)
and (1=(case when #EmployeeToggle = '2' then 1 else 0 end) or Field2 =
#Employee_ID)
These work great (admittedly I copied and pasted these examples), but at the expense of run time.
My final thought, and the way others have done it at my org, is to create two scripts that are identical except for the field used in the where clause. So, if #EmployeeToggle = '1' it will run the first script and if it's '2' it will run the second. I haven't tried that yet, but I assume the runtime will be closer to the 8 seconds at the expense of some ugly code.
Thanks for the help.
Why not just use a single query?
select t.*
from table1
where #EmployeeToggle = '1' and field_1 = #Employee_ID
union all
select t.*
from table1
where #EmployeeToggle <> '1' and field_2 = #Employee_ID;
By using union all, SQL Server should use indexes for each subquery -- and if you have indexes on the fields, the query should be fast.
You can stay with static SQL when using CASE expression in SELECT then filter it.
SELECT *
FROM (
SELECT *,
CASE WHEN #EmployeeToggle = '1' THEN Field1 ELSE Field2 END AS Field1_2
FROM Table1
) t
WHERE
Field1_2 = #Employee_ID
Here is your dynamic query:
Declare #EmployeeToggle varchar(30)
Declare #Employee_ID varchar(30)
Declare #EmployeeField varchar(100)
set #EmployeeToggle = '1'
set #Employee_ID = '1166'
set #EmployeeField = case when #EmployeeToggle = '1' then 'Field1' else
'Field2' end;
DECLARE #SQLString VARCHAR(MAX)
SET #SQLString='select *
from Table1
where '+#EmployeeField+' = '+#Employee_ID+''
PRINT(#SQLString) --If you want to check actual query
EXEC(#SQLString)

SQL: Declaring multiple variables that will not all be used at the same time

I'm writing a query that multiple variables will need to be set for but not all used at the same time. It looks something like this.
Declare #SuveryID as Int
Declare #StateAbbrev as Varchar
Declare #InvStart as Date
Declare #InvEnd as Date
Set #SuveryID = ''
Set #StateAbbrev = ''
Set #InvStart = ''
Set #InvEnd = ''
What I'm wanting it to do is whenever survey ID has a value in it, the others will be ignored. And whenever #StateAbbrev, #InvStart, and #InvEnd have a value, #SurveryID is ignored.
One way would be like...
if #SuveryID is null
begin
select *
from YourTable
where <all your other variables>
end
else
begin
select *
from YourTable
where Column = #SuveryID
end
Another way would be to set the variables to NULL when #SuveryID is not null and then use a catch all query. These are called Kitchen Sink queries and that article from Aaron Bertrand is worth a read for sure.
if #SuveryID is not null
begin
set #StateAbbrev = null
set #InvStart = null
<set all other variables to null>
end
select *
from YourTable
where (Column = #SuveryID or #SuveryID is null)
and (Col2 = #StateAbbrev or #StateAbbrev is null)
and <continue for all variables>

how to use declared variable to select data from another table in case when condition?

I made select query in which i want to select data based on condition.For this i declared one variable and set value of that variable in else part.I want to use that variable for further select in same else part how can i achieve this?Please Help
declare #stateid int
select CASE WHEN MstCustomerAddressInfo.StateId is null
THEN 24
ELSE set #stateid = MstCustomerAddressInfo.StateId
select mststate.statecode from mststate where MstState.StateId = #stateid
END AS StateCode
No, you can't have SET inside a CASE expression. Even you can't have multiple statements.
Same query you can write as following.
declare #stateid int
select CASE
WHEN MstCustomerAddressInfo.StateId is null THEN 24
ELSE
-- set #stateid = MstCustomerAddressInfo.StateId
(select mststate.statecode
from mststate
where MstState.StateId = MstCustomerAddressInfo.StateId)
END AS StateCode
from [Your_Table]

trigger sql null datetime variable

Iam writing an sql trigger with sql server
in this clause
IF (#EXON = '' OR #DATEDEB='' OR #DATEFIN= '') AND #N_CATComp =4
#DATEDEB #DATEFIN are datetime variable and the application accept null values for those both variable I want in this case null is not accepted , this works only for the first variable #EXON
plz help
IF (#EXON = '' OR ISNULL(#DATEDEB, '') ='' OR ISNULL(#DATEFIN, '') = '')
if it's null it'll return ''
To check if a variable #MyVar has it's value equal to null you should do this:
if (#MyVar IS NULL)
print '#MyVar has a NULL value'
else
print '#MyVar value is not NULL'
You should also check the documentation on the helper functions NULLIF and ISNULL.
IF (#EXON = '' OR #DATEDEB='' OR #DATEDEB IS NULL OR #DATEFIN= '' OR #DATEFIN IS NULL) AND #N_CATComp =4

Null or empty check for a string variable

if((isnull(#value,''))='')
I want to know whether the above piece of code works in checking if the variable is null or empty.
Yes, that code does exactly that.
You can also use:
if (#value is null or #value = '')
Edit:
With the added information that #value is an int value, you need instead:
if (#value is null)
An int value can never contain the value ''.
Use This way is Better
if LEN(ISNULL(#Value,''))=0
This check the field is empty or NULL
Yes, you could also use COALESCE(#value,'')='' which is based on the ANSI SQL standard:
SELECT CASE WHEN COALESCE(#value,'')=''
THEN 'Yes, it is null or empty' ELSE 'No, not null or empty'
END AS IsNullOrEmpty
DEMO
Yes, it works. Check the below example. Assuming #value is not int
WITH CTE
AS
(
SELECT NULL AS test
UNION
SELECT '' AS test
UNION
SELECT '123' AS test
)
SELECT
CASE WHEN isnull(test,'')='' THEN 'empty' ELSE test END AS IS_EMPTY
FROM CTE
Result :
IS_EMPTY
--------
empty
empty
123
Try this:
ISNULL(IIF (ColunmValue!='',ColunmValue, 'no units exists') , 'no units exists') AS 'ColunmValueName'
IF (LEN(#value) > 0) PRINT 'Variable is not null and not empty'
You can try
<column_name> is null
in the where clause.
You can try this.....
DECLARE #value Varchar(100)=NULL
IF(#value = '' OR #value IS NULL)
BEGIN
select 1
END
ELSE
BEGIN
select 0
END
declare #sexo as char(1)
select #sexo='F'
select * from pessoa
where isnull(Sexo,0) =isnull(#Sexo,0)