Condition on the WHERE clause - sql

My script has a variable that does not always contain a value. If there is a value, I need an extra WHERE clause.
DECLARE #identityUserIds NVARCHAR;
SELECT #identityUserIds = (SELECT TOP (1) [userIdsCsv] FROM [identityUsers])
SELECT *
FROM [Users]
-- IF (!ISNULL(#identityUserIds) OR #identityUserIds != '')
WHERE [ID] in (#identityUserIds)
-- ELSE (no extra condition)
How can I do that?

A common way to do this is:
... where #identityUserIds is null or ID in (#identityUserIds)

I think this can simply be done with an OR:
SELECT *
FROM [Users]
WHERE Len(ISNULL(#identityUserIds,''))=0
OR [ID] IN (#identityUserIds)
But note that #Rhumborl's comment is correct, the IN statement will not work with a string. Unfortunatly I have no immediate solution for that problem.

...where ID in (ISNULL(#identityUserIds,ID))

Related

Using Common Table Expression and IF EXISTS

I am running a query similar to
DECLARE #VARIABLE NVARCHAR(50) = 'VALUE';
WITH MYCTE_TABLE (Column1,Column2)
AS
SELECT
(ColumnA, Column B
FROM
SomeTable
WHERE
ColumnA = SomeValue)
IF EXISTS(SELECT ColumnZ FROM AnotherTable WHERE Columnz = SomeNumbers)
BEGIN
SELECT * FROM MYCTE_TABLE
END
ELSE
BEGIN
MYSUBQUERY2
END
...
However, I keep getting the following error:
Incorrect syntax near the keyword 'IF'.
Each subquery works well when run independently. It seems the use of a common table expression before the IF EXISTS is causing the issue.
Any help please?
I really doubt, that this is the best approach... You tried to clean and shorten this for brevitiy (thumbs up for this!), but the given information is - maybe - not enough.
You cannot use a CTE in different queries. A CTE is fully inlined as part of the query...
But you could write your values into a table variable like here:
DECLARE #tbl TABLE(Column1 INT, Column2 VARCHAR(100)); --Choose appropriate types
INSERT INTO #tbl
SELECT ColumnA, ColumnB FROM SomeTable WHERE ColumnA=SomeValue;
This table variable can be used in later queries (but in the same job!) like any other table:
SELECT *
FROM SomeTable AS st
INNER JOIN #tbl AS tbl ON ...
... or similiar usages...
Another approach might be this
SELECT Column1,Column2 INTO #SomeTempTable FROM SomeWhere
This will write the result of the SELECT into a temp table (which is session wide).
I'm quite sure, that there might be a better (set-based) approach... Are the two sub-queries identical in their result set's structure? If so, you might use UNION ALL and place your "IF EXISTS" as a WHERE-clause to each sub query.
IF is control flow. WITH is within a query. You can do:
IF EXISTS (SELECT ColumnZ FROM AnotherTable WHERE Columnz=SomeNumbers)
BEGIN
WITH MYCTE_TABLE (Column1,Column2)AS
SELECT (ColumnA, Column B FROM SomeTable WHERE ColumnA=SomeValue)
MYSUBQUERY1
END;
ELSE
BEGIN
WITH MYCTE_TABLE (Column1,Column2)AS
SELECT (ColumnA, Column B FROM SomeTable WHERE ColumnA=SomeValue)
MYSUBQUERY2
END;
Or you could use a temporary table or table variable to store the values.

SELECT statement having where clause with dynamic condition

I have a small select query which picks data from a table as per the parameter passed to a procedure.
DECLARE #flgParam bit
.
.
SELECT *
FROM tablename
WHERE flgRequired like <If #flgparam is 0 then 1 or zero , Else 1>
what is the best way to construct the where clause
I'm thinking something like this:
SELECT *
from tablename
where #flgparam is null or #flgcolumnval = #flgparam;
#flgparam is declared as a bit, so it can only take on the values of NULL, 0, and 1.
EDIT:
I'm trying to understand the logic. Adapted for the right names:
SELECT *
from sample
where (#flgparam = 0 and flgRequired is not null) or
(coalesce(#flgparam, 1) = 1 and flgRequired = 1)
The like is unnecessary; you can do strict equality.
A bit rough, but it should work, based on requirements:
select
S.itemname
,S.flgrequired
from
sample S
where
(S.flgRequired >= #flgParam)
Tested on sqlfiddle.
You cant use variables to substitute columns in the querys, to achieve that you should create your query as a string #QUERY and execute it using exec #QUERY

Select a column if other column is null

I need to select a field called ProgramID from a table and if the ProgramID is NULL then I need to select the value in the InterimProgramID from the same table and alias it as ProgramID.
How can I make a conditional SELECT statement to do this?
You need the ISNULL function.
SELECT ISNULL(a, b)
b gets selected if a is null.
Also, you can use the WHEN/THEN select option, lookup in BOL. Essentially: its c switch/case block meets SQL.
select COALESCE ( ProgramID , InterimProgramID ) as 'ProgramID'
You can use either the ISNULL function or the COALESCE function. They both do pretty much the same thing, however ISNULL only takes two parameters and COALESCE takes multiple parameters (returning the first non-null it encounters). Both try the first param, then the second, (and COALESCE continues on)
DECLARE #IAMNULL VARCHAR
DECLARE #IAMNOTNULL VARCHAR
SET #IAMNOTNULL = 'NOT NULL'
SELECT ISNULL(#IAMNULL, #IAMNOTNULL)
--Output: 'NOT NULL'
DECLARE #IAMNULLALSO VARCHAR
SELECT COALESCE(#IAMNULL, #IAMNULLALSO, #IAMNOTNULL)
--Output: 'NOT NULL'
SELECT ProgramID
FROM a_table
WHERE ProgramID IS NOT NULL
UNION
SELECT InterimProgramID AS ProgramID
FROM a_table
WHERE ProgramID IS NULL;
Coalesce('zzz-' + ProgramID, InterimID) as programID will still ignore ProgramID even if you have a pretext value. It's a cool little function
There is also:
Select NVL(Column_A, Column_B) From 'schema'.'table_name'
The NVL( ) function is available in Oracle, and not in MySQL or SQL Server. This function is used to replace NULL value with another value. It is similar to the IFNULL Function in MySQL and the ISNULL Function in SQL Server.
https://www.1keydata.com/sql/sql-nvl.html
You can also use IFNULL function
select IFNULL(ProgramId,interimId) as ProgramId

Changing Case of Strings (Lower to Upper) in SQL Server

I have 2 databases, one with lowercase data and another with uppercase data.
DECLARE #NAME VARCHAR(40)
SELECT #NAME = UPPER(SELECT NAME FROM DELETED)
By executing SELECT NAME FROM DELETED, I am selecting data that is lower case.
By executing SELECT #NAME = UPPER(SELECT NAME FROM DELETED), I would want to select uppercase data on the query inside the UPPER().
Question is can I use the UPPER() with the SELECT, like the query above?
How about
SELECT UPPER(NAME) FROM DELETED
instead of
UPPER(SELECT NAME FROM DELETED)
You'll need an extra pair of brackets
Select #NAME = UPPER((SELECT NAME FROM DELETED));
(Not that I'd do it that way, see Lukas's answer for a better approach).
Use
SELECT #pNAME = UPPER([NAME]) FROM DELETED

SQL Statement Match Anything

I use a regex in my SQL statements for an app that look like this
SELECT * FROM table WHERE id = {{REPLACEME}}
However, sometimes I'm not giving a parameter to replace that string with. Is there a way to replace it with something that matches anything. I tried *, but that does not work.
SELECT * FROM table WHERE id = id will match all rows that have non-null id
SELECT * FROM table WHERE id = id OR id IS NULL will match all rows.
id is probably a primary key, so you can probably use the former.
Replace {{REPLACEME}} with
[someValidValueForYouIdType] OR 1=1
I can only describe my solution with an example. The #AllRec is a parameter:
Declare #AllRec bit
set #AllRec = {0|1} --as appropriate
SELECT *
FROM table
WHERE
(
id = {{REPLACEME}}
and #AllRec = 0
) OR (
#AllRec = 1
)
In this solution, if #AllRec is 1 then everything is returned, ignoring the id filter. If #AllRec is zero, then the id filter is applied and you get one row. You should be able to quickly adapt this to your current regex solution.
Using the Regex-Replace option opens you up to SQL Injection attacks.
Assuming your language has support for parameterized queries, try this modified version of Jacob's answer:
SELECT * FROM table WHERE (id = #id OR #id IS NULL)
The catch is that you'll always have to provide the #id value.
SELECT field1, field2
FROM dbo.yourTable
WHERE id = isnull(#var, id)
Not sure what language your using, and this code kind of scares me but...
var statement = "SELECT * FROM table";
If REPLACEME is not empty Then
statement += " WHERE id = {{REPLACEME}}"
End If