How to use table variable in a NOT IN sql statement - sql-server

I am trying to use the table variable #notified in a NOT IN where clause like this....
DECLARE #notified TABLE (DMT_ID INT)
INSERT INTO #notified
SELECT [DMT_ID]
FROM [dbo].[PU_Transaction]
WHERE [PU_TransactionStatus] = 3
SELECT * from #notified
SELECT [NRO_TRANSACCION]
FROM [dbo].[TRANSACCION]
WHERE [NRO_TRANSACCION] NOT in (#notified)
But I am getting this error in the last SELECT
Must declare the scalar variable "#notified".
What is wrong ? How can this be solved.

You need to use this:
SELECT [NRO_TRANSACCION]
FROM [dbo].[TRANSACCION]
WHERE [NRO_TRANSACCION] NOT IN (SELECT DMT_ID FROM #notified)
You need to put a SELECT statement in the NOT IN clause - not just a table variable name...

select x from y where x not in (select x from z)
You should have two selects to use a not in.

Related

How to use declared variables in INNER SELECT Statement in Snowflake?

How to use SELECT Sub-Query in alias for a column?
Here's my script:-
/*Declaring variables:*/
SET period= '3';
SET smryseg=concat('sku',$period,'_smry');
SET spend= concat('sku',$period,'')
/*Printing it:*/
SELECT $period; /* #O/P: 3 */
SELECT $smryseg; /* #O/P: sku3_smry */
SELECT $spend; /* #O/P: sku3_spend */
/*now I want to use this variable in my INNER SELECT query:*/
create table IDENTIFIER ($smryseg) as
SELECT sum(spend) as (SELECT $spend)
FROM my_table;
Here, the last query is giving me an error, I also tried using IDENTIFIER, CONCAT, SUBSRING, $ ,removing parenthesis and much more.
I just want the name of column 'sum(spend)' obtained as 'sku3_spend' i.e in dynamic format
You can rename the column afterwards. Here's a self-contained example:
set spend_col='sku3_spend';
create or replace table t as select sum(spend) as x from values(1),(2),(3) s(spend);
alter table t rename column x to identifier($spend_col);
UPDATE
You can store dynamically named columns in an object:
set spend_col='sku3_spend';
create or replace table t as
select object_construct($spend_col, sum(spend)) data
from values(1),(2),(3) s(spend);
select data:sku3_spend from t;

How to loop with different values in T-SQL query?

I have some specific set of values that I want to filter on a column, I don't want to do an 'in' clause in SQL Server. I want to use loop to pass in different set of values each time.
For example if there is a name column in my data, and I want to run query 5 times with different filter value.
Please look at the loop query attached below.
DECLARE #cnt INT = 1;
WHILE #cnt < 94
BEGIN
SELECT Name, COUNT(*) AS Number_of_Names
FROM Table
WHERE name IN ('John')
AND value IS NOT NULL
GROUP BY Name
SET #cnt = #cnt + 1;
END;
I want to pass in different values under 'name' column at each loop like john in the case above, then mary in the next loop likewise based on set of values I pass in the variable like #values = John,Mary,Nicole,matt etc..
Considering the comments on your question, this should give you an idea on how to achieve a solution without using loops and still get all the names even when the name is not present on the table.
SELECT Name,
COUNT(value) AS Number_of_Names --Only count when value is not null
FROM (VALUES('John'), ('Mary'), ('Nicole'), ('Matt'))Names(name) --This can be replaced by a table-valued parameter or temp table.
LEFT JOIN Table t ON Names.name = t.name
--WHERE name IN ('John') /*No longer needed*/
--AND value IS NOT NULL /*Removed this because it would make the OUTER JOIN behave as an INNER JOIN*/
GROUP BY Name;

How do SQL Server variables work?

I have a table with salary of multiple employees.
I need to calculate score for these employees using a derived number (mean and stddev) and include it as a new column.
I know I can do this in the select statement, but if I wanted see if I can use variables.
So that changes can be made dynamically. I am new to SQL and just trying to learn things here.
declare #Weight int,
#weight2 int,
#Mean int,
#StdDevn int,
#Variance int
set #Weight = 30
set #weight2 = (POWER(#weight,2)/100)
SELECT #Mean = AVG(salary) FROM [live].[dbo].[salary]
SELECT #StdDevn = STDEV(salary) FROM [live].[dbo].[salary]
SELECT #Variance = (POWER(#StdDevn,2)/100)
-- I should include some code here so that the above variable are passed to below query
SELECT * FROM [live].[dbo].[salary], (([salary]-#Mean)/#StdDevn)
Error:
Must declare variable #Mean, Incorrect syntax near '-'.
The problem you have is how you are trying to select.
The variable #Mean is declared and it would work if the final select would be something like below:
SELECT *,
(([salary]-#Mean)/#StdDevn) as SomeOtherCol
FROM [live].[dbo].[salary]
The SomeOtherCol will be then shown as the last column of your result set.

I am trying to use an IF statement using a select IN clause. What is he correct syntax for the following T-SQL statement?

Using SQL Server 2000; I am trying to determine the action if a value in a field of the INSERTED record matches one of several distinct values in a field in a table. Field y in tableB could be say 'one', 'two' or 'three'. The INSERTED record must be a single record, and therefore the field x must be a single value. Hence, given the code snippet below, what is the correct syntax? In particular where do the "()" go in the IF statement?
if select x from INSERTED in (select y from tableB)
and <another condition>
begin
<some code>
end
The correct syntax is
IF EXISTS (SELECT * FROM TABLE1 WHERE X IN (1,2))
Begin
-- code
End
You can store the individual flag in variables and use that in IF condition.
Declare #chkExist int
Select #chkExist = Count(*) from tableA x in (select y from tableB)
if ((#chkExist > 0) and (<another condition>))
begin
<some code>
end
Try a "where exists" instead of "IN"
if exists ( select null from tableA taAlias where (select null from tableB tbAlias where tbAlias.y = taAlias.x ) )
and 1=1
begin
Select 1 as 'YouNeedAtLeastOneLineOfCodeInThisBeginEnd'
end

How Do I Use a Variable in a Select Statement?

When I run the following code I get the error : Incorrect syntax near '#num_to_remove'.
Any idea why this doesn't work?
Thanks in advance,
Matt
DECLARE #num_to_remove INT
SET #num_to_remove = 2
-- get em_ids for records to delete
WITH em_ids
AS (SELECT TOP #num_to_remove em_id
FROM irs_self_cert_em sc
WHERE sc.date_cert_loc IS NULL
AND sc.date_first_cert_email_sent < '2014-10-03')
SELECT * FROM em_ids
In regular tSQL, you can only use variables to represent values, not column names or other objects. I know the numeric value for a "TOP" clause seems like it should qualify but it doesn't.
To use a variable in this way, you have to do Dynamic SQL.
Try this (Note: I haven't tested it. You can try similar this)
DECLARE #num_to_remove INT
SET #num_to_remove = 2
-- get em_ids for records to delete
EXEC
(
'WITH em_ids
AS (SELECT TOP ' + CAST(#num_to_remove AS varchar(10) + 'em_id
FROM irs_self_cert_em sc
WHERE sc.date_cert_loc IS NULL
AND sc.date_first_cert_email_sent < ''2014-10-03'')
'
)

Resources