How to write nested if statements in SQL Server 2008 - sql

I have a query in SQL Server 2008 like below:
declare #checkValue int = 1
IF (#checkValue = 1)
(
IF OBJECT_ID('tempdb..#newtable') IS NOT NULL DROP TABLE #newtable
Select Id
into #newtable
From #oldtable
);
This is not working since the second if clause which is inside the main IF clause. How can I fix it and use nested if statements like that?
Any help would be appreciated. Thanks

Almost, but you need BEGIN and END instead of parenthesis:
declare #checkValue int = 1
IF (#checkValue = 1)
BEGIN
IF OBJECT_ID('tempdb..#newtable') IS NOT NULL DROP TABLE #newtable
Select Id
into #newtable
From #oldtable
END;

Related

There is already an object named '#BaseData' in the database

Below is a snippet of my code.
I am wanting to filter my data based upon a variable.
When I try to run the code, it returns an error of "There is already an object named '#BaseData' in the database.". I am not sure as to why this is the case; I have put extra checks within the IF statements to drop the temp table if it already exists but to no avail.
Are you able to help or provide an alternative solution please?
DECLARE #Variable AS VARCHAR(20) = 'Example1'
IF OBJECT_ID(N'TEMPDB..#BaseData') IS NOT NULL
DROP TABLE #BaseData
IF #Variable = 'Example1'
BEGIN
SELECT
*
INTO
#BaseData
FROM
[Database].[schema].[table]
END
IF #Variable = 'Example2'
BEGIN
SELECT
*
INTO
#BaseData
FROM
[Database].[schema].[table]
WHERE
[column] = 1
END
IF #Variable = 'Example3'
BEGIN
SELECT
*
INTO
#BaseData
FROM
[Database].[schema].[table]
WHERE
[column] = 0
END
While code is compiled by SQL, creation of same #table is found in each condition so it doesn't work.
One possible solution would be to create table and than insert data conditionally.
-- DROP TEMP TABLE IF EXISTS
IF OBJECT_ID(N'TEMPDB..#BaseData') IS NOT NULL
DROP TABLE #BaseData
GO
-- CRATE TEMP TABLE WITH TempId, AND SAME STRUCTURE AS YOUR TABLE
SELECT TOP 0 CONVERT(INT, 0)TempId, * INTO #BaseData FROM TestTable
-- DECLARE VARIABLE
DECLARE #Variable AS VARCHAR(20)= 'Example1'
-- INSERT DATA IN TABLE DEPENDING FROM CONDITION
IF (#Variable = 'Example1')
BEGIN
INSERT INTO #BaseData SELECT * FROM TestTable
END
IF (#Variable = 'Example2')
BEGIN
INSERT INTO #BaseData SELECT * FROM TestTable WHERE Id = 1
END
IF (#Variable = 'Example3')
BEGIN
INSERT INTO #BaseData SELECT * FROM TestTable WHERE Id = 2
END

Switch case with storing results into same table in SQL

I want to store the results into table with same name as per the condition. How to achieve the same ? Following is the code:
While executing it throws error that #a already exists.
IF #Input ='1'
BEGIN
drop #a
SELECT *
INTO #a
FROM table1
END;
ELSE IF #Input ='2'
BEGIN
drop #a
SELECT *
INTO #a
FROM table2
END;
You can use this solution using a global temporary table (maybe not the best / safest solution). The statements get executed with EXECUTE:
DECLARE #Input VARCHAR(20) = '1'
IF OBJECT_ID('tempdb..##a') IS NOT NULL
BEGIN
DROP TABLE ##a
END
IF #Input = '1'
EXEC ('SELECT * INTO ##a FROM table1;')
ELSE IF #Input = '2'
EXEC ('SELECT * INTO ##a FROM table2;')
-- you can implement steps here to create a local temporary table.
-- see: https://stackoverflow.com/questions/9534990/tsql-select-into-temp-table-from-dynamic-sql
SELECT * FROM ##a
Also have a look at this question: TSQL select into Temp table from dynamic sql. There is also described how you can get the data as local temporary table in two different ways (using a global temporary table or a view).
The problem using the EXECUTE function is leaving the scope.
try this
if object_id('tempdb..#a') is not null
drop table #a
IF #Input ='1'
BEGIN
SELECT *
INTO #a
FROM table1
END;
ELSE IF #Input ='2'
BEGIN
SELECT *
INTO #a
FROM table2
END;

how to insert cases into a table based on a parameter without duplicating the main select query?

I have a insert statement in sql server 2008 like below:
INSERT INTO MYTABLE
SELECT Id,Name,Date
FROM #temp
...joins...
where ...conditions...
I need to add a parameter to the code, and based on the parameter I will decide which table the output data should be inserted into. Check below:
declare #checkValue bit;
if (#checkValue = 1)
begin
INSERT INTO MYTABLE
SELECT Id,Name,Date
FROM #temp
...joins...
where ...conditions...
end
else
begin
INSERT INTO MY_OTHER_TABLE
SELECT Id,Name,Date
FROM #temp
...joins...
where ...conditions...
end
I handled the situation like above for now, however the main query is pretty long and I do not want to duplicate it, it does not look professional to me. I am looking for a better way to deal with such an issue. Any help or advice should be appreciated. Thanks.
You could use dynamic SQL (evil :), like so:
declare #cmd varchar(max) = '
INSERT INTO ' + #tableName + '
SELECT ...
';
execute (#cmd);
Or you create stored procedures (one statically INSERTs to table A, another one into table B >> code duplication) which are called depending on #checkValue, or a combination of both like here:
Stored procedure to insert values into dynamic table
create SP:
CREATE PROCEDURE ExampleSelect
AS
SELECT Id,Name,Date
FROM #temp
...joins...
where ...conditions...
GO
use insert..exec to insert data:
declare #checkValue bit;
if (#checkValue = 1)
begin
INSERT INTO MYTABLE
EXEC ExampleSelect
end
else
begin
INSERT INTO MY_OTHER_TABLE
EXEC ExampleSelect
end

T-SQL IF statement explanation

I'm really puzzled by this one!! I'm sure it's simple but really can't figure it out!!
DECLARE #jobid INT = 100
IF (#JobID >= 0)
BEGIN
SELECT * into #tmp FROM Persons
end
ELSE
BEGIN
SELECT * into #tmp FROM Persons1
end
It gives an error that the #tmp table already exists! Why it would validate both statements !
Of course my original query is huge and doing more, but that's a sample to illustrate my error.
Can anybody explain it please?
The #tmp table is not there, even when you try to drop it or change the name, still the engine validates both statements!
I'm using 2008 R2.
Thanks
Jason
You run it over Linked Server? Or you not deleted the one from previous run.
Try to create #tmp table prior to IF statement:
CREATE TABLE #tmp(fields...)
DECLARE #jobid INT = 100
IF (#JobID >= 0)
BEGIN
INSERT #tmp
SELECT * FROM Persons
end
ELSE
BEGIN
INSERT #Tmp
SELECT * FROM Persons1
end
or delete provious one
IF OBJECT_ID('tempdb..#tmp') IS NOT NULL
EXEC('DROP TABLE #tmp')
GO
DECLARE #jobid INT = 100
IF (#JobID >= 0)
BEGIN
SELECT * into #tmp FROM Persons
end
ELSE
BEGIN
SELECT * into #tmp FROM Persons1
end
#tmp may already be created in tempDB from previous runs of your query. If you are not using #tmp anywhere in your query prior to that block, you could do something like the following prior to that block of code to ensure it's always ready to go:
IF OBJECT_ID('tempDB..#tmp') IS NOT NULL
DROP TABLE #tmp

How do i use rowcount in Function in sqlserver?

I have faced a problem using rowcount in function in sql server 2000.
It shows an error like Invalid use of 'UNKNOWN TOKEN' within a function.
MY function is like this.
ALTER Function fnc_GetOpenShiftWorkID (#EMP_ID int,#Counter int,#date Datetime) returns int as
BEGIN
SET ROWCOUNT #Counter
declare #result int
if exists(select * from tbl_org_workinghrs WHERE EMP_ID=#EMP_ID and SDATE=#DATE)
BEGIN
select #result= WORK_ID
from tbl_org_working_hrs work_hrs
inner join tbl_org_shift_group sgroup on sgroup.WH_ID=work_hrs.WORK_ID
inner join tbl_org_workinghrs workhrs on workhrs.GROUP_ID=sgroup.GROUP_ID
WHERE EMP_ID=#EMP_ID
and SDATE=#DATE
order by
IN_START
END
ELSE
BEGIN
if exists(select * from tbl_org_workinghrs where EMP_ID=0)
BEGIN
select #result=WORK_ID
from tbl_org_working_hrs
WHERE IS_DEFAULTSHIFT=1
END
END
return #result
END
You want to get the value of the n'th row ordered by IN_START.
From SQL Server 2005 later you could use top(n) or row_number().
In SQL Server 2000 you can use a table variable with an identity ID field as a temp storage.
Something like this.
declare #T table
(
ID int identity,
WORK_ID int
)
insert into #T (WORK_ID)
select WORK_ID
from tbl_org_working_hrs work_hrs
inner join tbl_org_shift_group sgroup
on sgroup.WH_ID=work_hrs.WORK_ID
inner join tbl_org_workinghrs workhrs
on workhrs.GROUP_ID=sgroup.GROUP_ID
where EMP_ID=#EMP_ID and
SDATE=#DATE
order by IN_START
select #result = WORK_ID
from #T
where ID = #Counter