How to write the T-SQL below in SnowFlake
if exists (select top 1 1 from tableName)
This returns true or false
Update
I tried to run the if in the screenshot below in the Snowflake browser, but get the error:
https://docs.snowflake.com/en/sql-reference/snowflake-scripting/if.html
It depends on where you will use it:
create table tableName( id number);
SELECT exists (select top 1 1 from tableName);
-- returns false
insert into tablename values (1 );
SELECT exists (select top 1 1 from tableName);
-- returns true
The direct equivalent of IF:
-- SQL Server
if exists (select top 1 1 from tableName)
-- come code
is an anonymous block with branch construct(Snwoflake Scripting):
BEGIN
IF (EXISTS(select top 1 1 from tableName)) THEN
-- some code
END IF;
END;
If Classic WebUI is used then Using Snowflake Scripting in SnowSQL and the Classic Web Interface:
EXECUTE IMMEDIATE $$
BEGIN
IF (EXISTS(select top 1 1 from tableName)) THEN
RETURN 1;
END IF;
END;
$$;
This expression evaluates true if (and only if) the table tablename contains any data (that is 1 or more rows).
IF EXISTS (
SELECT TOP 1
1
FROM tablename
)
It should have the same effect as
IF EXISTS (
SELECT
*
FROM tablename
)
I don't know but I would expect Snowflake to be smart enough to do no more than determine if there are results in either case.
The second form is the common SQL idiom in my experience.
Related
i have this procedure in sql.
the requirment is:
if condition (for example i put 1=1 ..) then [run another procedure or function that will random from table with values one value and return it.] else 1
for example:
case when 1=1 then (dbo.myFunc #input) else 1
this is myTable: '1','2','3'
and i want this function to random from it one value
CREATE FUNCTION dbo.myFunc (#input int)
RETURNS int
AS BEGIN
declare #rndValue int
set #rndValue = (SELECT top 1 * FROM myTable ORDER BY newID())
RETURN #rndValue
END
the problem is that in function i cannot run newID(), and if i want to use procedure instead of function i cannot run it from case statement.
what are u suggest.? thanks alot.
I think you need a code like this:
set x = case when 1=1 then (select top(1) val from myTable order by newid()) else 1 end;
SQL Fiddle
I have created a #table inside a stored procedure using a select * into statement. The table is shown fine, but when I start using an if statement, it says "Invalid Column Name". Why is this happening, the columns are all available in the table I created.
Can anyone tell me whats the issue ?
I have tried using select * from #table, all the columns and its values are present.
I have also tried update #Table and change several values. It works fine till here.
Only when I use the if statement, its showing the error,
UPDATE #SMSB_temp
SET Status = '09'
WHERE RenewStatus = '03'
IF NOT EXISTS (SELECT * FROM #SMSB_temp)
BEGIN
IF Status = '09' AND AvailableBalance > #SMSBRenewalCharges
BEGIN
END
END
You have to write IF statement like below. Your code is currently not referring to any table in the IF statement. I hope you want to check if there is a row with Status = '09' and AvailableBalance > #SMSBRenewalCharges.
DECLARE #Check bit
SET #check = (SELECT TOP 1 1
FROM #SMSB_temp
WHERE Status = '09' AND AvailableBalance > #SMSBRenewalCharges)
IF #check = 1
BEGIN
...
END
As #squirrel suggested in the comments, you can simply write as below:
IF EXISTS ( SELECT TOP 1 1
FROM #SMSB_temp
WHERE Status = '09' AND AvailableBalance > #SMSBRenewalCharges)
BEGIN
...
END
i have a stored procedure where i insert results of many controls in temporary table, at the end i have to check if all table exists and if are empty or not
i start with
IF(NOT EXISTS (SELECT TOP 1 1 FROM #tblControllo1)
AND NOT EXISTS (SELECT TOP 1 1 FROM #tblControllo2)
AND NOT EXISTS (SELECT TOP 1 1 FROM #tblControllo3)
AND NOT EXISTS (SELECT TOP 1 1 FROM #tblControllo4)
...
but i get error when some table does not exists so i have to mix those chek with
OBJECT_ID('tempdb..#tblControllo1') IS NOT NULL
but i don't find an elegant way to do it other than
DECLARE #controllo BIT = 1
IF OBJECT_ID('tempdb..#tblControllo1') IS NOT NULL
IF(EXISTS (SELECT TOP 1 1 FROM #tblControllo1) )
SET #controllo = 0
IF OBJECT_ID('tempdb..#tblControllo2') IS NOT NULL
IF(EXISTS (SELECT TOP 1 1 FROM #tblControllo2) )
SET #controllo = 0
IF OBJECT_ID('tempdb..#tblControllo3') IS NOT NULL
IF(EXISTS (SELECT TOP 1 1 FROM #tblControllo3) )
SET #controllo = 0
....
IF(#controllo = 1)
-- do stuff
is there a better way to do it?
The biggest problem is that you can't execute directly an SQL with SELECT of a table that may not exist because it will throw an error when trying to execute it. The following script uses a Dynamic SQL with a cursor to validate each table you need, breaking at the first failed condition.
DECLARE #AtLeastOneValidationFails BIT = 0
DECLARE TemporaryTableCursor CURSOR FOR
SELECT
G.TemporaryTableName
FROM
(VALUES
('#FirstTable'), -- Your tables to validate here
('#SecondTable'))
AS G (TemporaryTableName)
DECLARE #TemporaryTableName VARCHAR(100)
OPEN TemporaryTableCursor
FETCH NEXT FROM TemporaryTableCursor INTO #TemporaryTableName
WHILE ##FETCH_STATUS = 0
BEGIN
IF OBJECT_ID('tempdb..' + #TemporaryTableName) IS NULL
BEGIN
SET #AtLeastOneValidationFails = 1
BREAK
END
DECLARE #DynamicSQL NVARCHAR(MAX) = N'
IF NOT EXISTS (SELECT 1 FROM ' + #TemporaryTableName + ')
SET #ExistFails = 1'
EXEC sp_executesql
#stmt = #DynamicSQL,
#params = N'#ExistFails BIT OUTPUT',
#ExistFails = #AtLeastOneValidationFails OUTPUT
IF #AtLeastOneValidationFails = 1
BREAK
FETCH NEXT FROM TemporaryTableCursor INTO #TemporaryTableName
END
CLOSE TemporaryTableCursor
DEALLOCATE TemporaryTableCursor
SELECT
AtLeastOneValidationFails = #AtLeastOneValidationFails
This will ensure that the tables exists before issuing the SELECT (thus not failing). Please be careful with table names as this is executing Dynamic SQL.
You can wrap this in a procedure and pass the table names as parameter so you don't repeat it everywhere. You can also edit it to return the failed table name so you can debug it properly.
PD: You can omit the TOP N when doing an EXISTS as the engine is smart enough to just check if the resulting query has at least 1 row.
i am trying to create sql server procedure with if statement.
i am new to the ms sql server however i tried with the following statements but it gave me the below error Msg 116, Level 16, State 1, Procedure te, Line 9
Only one expression can be specified in the select list when the subquery is not introduced with EXISTS.
here is the code i wrote
CREATE PROCEDURE test as
BEGIN
SET NOCOUNT ON;
if (select COUNT(load),load,contractor_id from [test].[dbo].[cont]
group by load,contractor_id
having load = (select MIN(load)from [test].[dbo].[cont])
) > 1
begin
SELECT top 1 COUNT(*),load ,contractor_id,name
FROM [test].[dbo].[cont]
group by load,contractor_id,name
having load = (select MIN(load)from [test].[dbo].[cont])
ORDER BY NEWID()
end
ELSE
BEGIN
SELECT top 1 COUNT(*),load ,contractor_id,name
FROM [test].[dbo].[cont]
group by load,contractor_id,name
having load = (select MIN(load)from [test].[dbo].[cont])
END
END
GO
can anyone help please
As the error says you cannot have multiple column selected when you use IF condition. In your first IF condition you are selecting multiple columns, however if conditions requires to have a query that can lead to one value. Other option is you have to use IF EXISTS, that can check count >1 as below
IF (SELECT COUNT(load),load,contractor_id
FROM [test].[dbo].[cont]
GROUP BY load,contractor_id
HAVING load = (SELECT MIN(load)
FROM [test].[dbo].[cont])
AND COUNT(load) >1)
Another thing what I noticed is you are excecuting the query which calculates the min of load multiple times. You can avoid that by storing it in a variable and use it further.
I have modified the procedure as below. Check if this works or not.
CREATE PROCEDURE test as
BEGIN
SET NOCOUNT ON;
DECLARE #count INT
DECLARE #minload INT
SELECT #minload = MIN(load)from [test].[dbo].[cont]
SELECT #count = COUNT(load) from [test].[dbo].[cont]
GROUP BY load,contractor_id
HAVING load = #minload
IF (#count) > 1
BEGIN
SELECT top 1 COUNT(*),load ,contractor_id,name
FROM [test].[dbo].[cont]
WHERE load = #minload
GROUP BY load,contractor_id,name
ORDER BY NEWID()
END
ELSE
BEGIN
SELECT top 1 COUNT(*),load ,contractor_id,name
FROM [test].[dbo].[cont]
GROUP BY load,contractor_id,name
HAVING load = #minload
END
END
UPDATE
Based on your comments, I suppose you can get the result with one simple query as below.
;WITH minLoad(load)
AS
(
SELECT MIN(load)
FROM [test].[dbo].[cont]
)
SELECT TOP 1 COUNT(*),c.load ,c.contractor_id,c.name
FROM [test].[dbo].[cont] c, minLoad
WHERE c.load = minLoad.load
ORDER BY NEWID();
Once again.. i have the trigger below which has the function to keep/set the value in column esb for maximum 1 row to value 0 (in each row the value cycles from Q->0->R->1)
When i insert more than 1 row the trigger fails with an "Subquery returned more than 1 value. This is not permitted when the subquery follows" error on row 38, the "IF ((SELECT esb FROM INSERTED) in ('1','Q'))" statment.
I understand that 'SELECT esb FROM INSERTED' will return all rows of the insert, but do not know how to process one row at a time. I also tried it by creating a temporary table and iterating through the resultset, but subsequently found out that temporary tables based on the INSERTED table are not allowed.
any suggestions are welcome (again)
set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
go
ALTER TRIGGER [TR_PHOTO_AIU]
ON [SOA].[dbo].[photos_TEST]
AFTER INSERT,UPDATE
AS
DECLARE #MAXCONC INT -- Maximum concurrent processes
DECLARE #CONC INT -- Actual concurrent processes
SET #MAXCONC = 1 -- 1 concurrent process
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON
-- If column esb is involved in the update, does not necessarily mean
-- that the column itself is updated
If ( Update(ESB) )
BEGIN
-- If column esb has been changed to 1 or Q
IF ((SELECT esb FROM INSERTED) in ('1','Q'))
BEGIN
-- count the number of (imminent) active processes
SET #CONC = (SELECT COUNT(*)
FROM SOA.dbo.photos_TEST pc
WHERE pc.esb in ('0','R'))
-- if maximum has not been reached
IF NOT ( #CONC >= #MAXCONC )
BEGIN
-- set additional rows esb to '0' to match #MAXCONC
UPDATE TOP(#MAXCONC-#CONC) p2
SET p2.esb = '0'
FROM ( SELECT TOP(#MAXCONC-#CONC) p1.esb
FROM SOA.dbo.photos_TEST p1
INNER JOIN INSERTED i ON i.Value = p1.Value
AND i.ArrivalDateTime > p1.ArrivalDateTime
WHERE p1.esb = 'Q'
ORDER BY p1.arrivaldatetime ASC
) p2
END
END
END
Try to rewrite your IF as:
IF EXISTS(SELECT 1 FROM INSERTED WHERE esb IN ('1','Q'))
...