I am trying to create an if else script to skip a record if there is a specific value in a column of the table and continue to insert records into a different table.
How do I create the script to perform this action?
IF EXISTS (Select * From Table A where X =1)
BEGIN
Do nothing
END
ELSE
BEGIN
INSERT INTO TABLE Y
SELECT * FROM TABLE Z
END
Instead, write a single statement:
INSERT INTO TABLE Y
SELECT *
FROM TABLE Z
WHERE NOT EXISTS (Select 1 From Table A where X = 1);
The conditional is not needed at all.
If you want it in a proc to execute, use it this way
create procedure usp_insert
as
BEGIN
declare #rowcount int = (Select count(*) From TableA where X <>'1')
Begin
if #rowcount>=1
INSERT INTO TABLE Y
SELECT * FROM TABLE Z
end
END
Related
I am trying to insert select query result into a temporary table inside the while loop. But below query gives me this error:
There is already an object named '#TT' in the database.
DECLARE #V_START INT = 1;
DROP TABLE #TT
WHILE(#V_START < 4)
BEGIN
SELECT * INTO #TT
FROM Table
WHERE Column = #V_START;
SET #V_START = #V_START + 10;
END
SELECT * FROM #TT
every time your loop is executed a temporary table will create, but first-time execution the temp table does not exist command run successfully and you give the error in the second round of loop execution.
You can try it like below :
DECLARE #V_START INT = 1;
DROP TABLE IF EXISTS #TT;
CREATE TABLE #TT
(
--your columns
)
WHILE(#V_START < 40)
BEGIN
INSERT INTO #TT
(
--your columns
)
SELECT --your columns
FROM Table
WHERE Column = #V_START;
SET #V_START = #V_START + 10;
END
SELECT * FROM #TT
but better solution is using select into with condition for inserting data to temp table:
DROP TABLE IF EXISTS #TT
SELECT * INTO #TT
FROM Table
WHERE Column % 10 = 0 AND Id < 10
SELECT * FROM #TT
I am trying to capture if my SQL Query have 0 rows or multiple rows. If it has 0 rows then I will insert, if 1 will perform an update, if > 1 will perform additional analysis.
Is there a way I can see if my query resulted in x results or no results in automation anywhere?
Any assistance will be appreciated.
You can make use of if exists and if not exists and check if rows exists or not, or even if there are multiple before doing the insert.
Here is a simple example using if not exists where if the row doesn't exist on dbo.Table it will insert a row. If it already exists then the ID will be logged to an Error table.
declare #InsertID int = 5, #Name nvarchar(max) = 'some name'
if ((select count(1) from dbo.Table where ID = #InsertID) > 1) -- detect error; more than one record for an id
begin
insert into dbo.Error (ErrorID, ErrorDate)
select #InsertID, getdate()
end
else if not exists (select 1 from dbo.Table where ID = #InsertID) -- no record exists for ID, insert it
begin
insert into dbo.Table (ID, Name)
select #InsertID, #Name
else if exists (select 1 from dbo.Table where ID = #InsertID) -- update the single record
begin
update dbo.Table set Name = #Name where ID = #InsertID
end
A2019 returns the results of a SQL Query as a table...
You could have an if statement right after your query which checks to see if the row count of the returned table is > 0 then take action accordingly.
I'm having some strange issues using IF / ELSE to determine which one or two SELECT statements to execute. The error message I'm getting when running the full statement is that my temporary table already exists, but that does not occur if I run two separate executions of two separate IF statements.
Here is the code in SQL Server:
IF (select BusinessDayCount from Calendartbl) <= 1
BEGIN
SELECT * into #temp1
FROM PreviousMonthTbl
END
ELSE
BEGIN
SELECT * into #temp1
FROM CurrentMonthTbl
END
It's a "feature" of the syntax checking in SQL Server. You simply cannot "create" a #temporary table twice within the same batch.
This is the pattern you need.
SELECT * into #temp1
FROM PreviousMonthTbl
WHERE 1=0;
IF (select BusinessDayCount from Calendartbl) <= 1
BEGIN
INSERT into #temp1 SELECT *
FROM PreviousMonthTbl
END
ELSE
BEGIN
INSERT into #temp1 SELECT *
FROM CurrentMonthTbl
END
If you prefer, you can also express the branch (in this case) as a WHERE clause:
SELECT * into #temp1
FROM PreviousMonthTbl
WHERE (select BusinessDayCount from Calendartbl) <= 1
UNION ALL
SELECT *
FROM CurrentMonthTbl
WHERE isnull((select BusinessDayCount from Calendartbl),2) > 1
You can't use SELECT INTO for a tables with same name in the same batch. Use a different name for a temporary table
IF EXISTS(
SELECT 1
FROM Calendartbl
WHERE BusinessDayCount <= 1
)
BEGIN
IF OBJECT_ID('tempdb.dbo.#PreviousMonthTbl') IS NULL DROP TABLE dbo.#PreviousMonthTbl
SELECT *
INTO #PreviousMonthTbl
FROM PreviousMonthTbl
END
ELSE
BEGIN
IF OBJECT_ID('tempdb.dbo.#CurrentMonthTbl') IS NULL DROP TABLE dbo.#CurrentMonthTbl
SELECT *
INTO #CurrentMonthTbl
FROM CurrentMonthTbl
END
From what I understand the problem is this:
When you run the below statement,
SELECT * into #temp1 FROM CurrentMonthTbl
you are creating a temp table on the fly.
If before that line you had a create table statement, then this Select into statement will fail because the table already exists.
If in your case you already have a temp table created, then try replacing:
SELECT * into #temp1 FROM CurrentMonthTbl
with:
Insert into #temp1
Select * from CurrentMonthTbl
Also look at There is already an object named '##Temp' in the database
You can use actual table in place of #temp1 table in if else statement. After that you can insert the data from actual to temp table and drop the actual table.
IF OBJECT_ID('tempdb..#temp1') is not null
drop table #temp1
IF (select BusinessDayCount from Calendartbl) <= 1
BEGIN
SELECT * into dbo.TempTable
FROM PreviousMonthTbl
END
ELSE
BEGIN
SELECT * into dbo.TempTable
FROM CurrentMonthTbl
END
select * into #temp1
from dbo.TempTable
IF OBJECT_ID('dbo.TempTable', 'U') is not null
drop table dbo.TempTable
I have a collection of rows that I get from a web service. Some of these rows are to be inserted, some are updates to existing rows. There is no way of telling unless I do a query for the ID in the table. If I find it, then update. If I don't, then insert.
Select #ID from tbl1 where ID = #ID
IF ##ROWCOUNT = 0
BEGIN
Insert into tbl1
values(1, 'AAAA', 'BBBB', 'CCCC', 'DDD')
END
ELSE
BEGIN
UPDATE tbl1
SET
A = #AAA,
B = #BBB,
C = #CCC,
D = #DDD
WHERE ID = #ID
END
I am trying to figure out the most effient way to update/insert these rows into the table without passing them into a stored procedure one at a time.
UPDATE 1
I should have mentioned I am using SQL Server 2005. Also if I have 300 records I don't want to make 300 stored procedure calls.
the most efficient way will be first try to update the table if it returns 0 row updated then only do insertion. for ex.
UPDATE tbl1
SET
A = #AAA,
B = #BBB,
C = #CCC,
D = #DDD
WHERE ID = #ID
IF ##ROWCOUNT = 0
BEGIN
Insert into tbl1
values(1, 'AAAA', 'BBBB', 'CCCC', 'DDD')
END
ELSE
BEGIN
END
Instead of paying for a seek first and then updating using another seek, just go ahead and try to update. If the update doesn't find any rows, you've still only paid for one seek, and didn't have to raise an exception, but you know that you can insert.
UPDATE dbo.tbl1 SET
A = #AAA,
B = #BBB,
C = #CCC,
D = #DDD
WHERE ID = #ID;
IF ##ROWCOUNT = 0
BEGIN
INSERT dbo.tbl1(ID,A,B,C,D)
VALUES(#ID,#AAA,#BBB,#CCC,#DDD);
END
You can also look at MERGE but I shy away from this because (a) the syntax is daunting and (b) there have been many bugs and several of them are still unresolved.
And of course instead of doing this one #ID at a time, you should use a table-valued parameter.
CREATE TYPE dbo.tbl1_type AS TABLE
(
ID INT UNIQUE,
A <datatype>,
B <datatype>,
C <datatype>,
D <datatype>
);
Now your stored procedure can look like this:
CREATE PROCEDURE dbo.tbl1_Update
#List AS dbo.tbl1_type READONLY
AS
BEGIN
SET NOCOUNT ON;
UPDATE t
SET A = i.A, B = i.B, C = i.C, D = i.D
FROM dbo.tbl1 AS t
INNER JOIN #List AS i
ON t.ID = i.ID;
INSERT dbo.tbl1
SELECT ID, A, B, C, D
FROM #List AS i
WHERE NOT EXISTS
(
SELECT 1
FROM dbo.tbl1 WHERE ID = i.ID
);
END
GO
Now you can just pass your DataTable or other collection from C# directly into the procedure as a single parameter.
From the collection of rows you get from the server find out which ones are already there:
select #id from tbl1 where id in (....)
Then you have a list of ids that are in the table and one that there are not in the table.
You will have then 2 batch operations: one for update, the other for insert.
what i understand is this :
at the front end u issue a single sql statement
ArrayofIDsforInsert = select ID from tbl1 where ID not in ( array of ids at the front end)
ArrayofIDsforUpdate = (IntialArrayofids at frontend) - (ArrayofIdsforInsert)
one insert into table and one update table...
now call the insert into table with ArrayofIds for insert
call the update table with ArrayofIds for update..
Suppose that I have a table my_table(id, x, y). I want to write a trigger to prevent updating the y col and setting it to a non-null value if x is already null. As SQL Server doesn't have a before update trigger, how can this be done? Apparently we can use an instead of trigger for this purpose, but how can we check the old and current values and decide whether we should raise an error or let the update execute normally?
Example:
Let's pretend we have this row in the DB:
1, null, null
Then this should fail (raise error)
update my_table set y = 'blah' where id = 1;
But this should succeed:
update my_table set y = null where id = 1;
I know the example isn't very meaningful, but it is similar to what I am trying to achieve.
This should work, but I am not sure what other edge conditions you need to handle:
create table my_table (id int identity, x varchar(20), y varchar(20))
go
CREATE TRIGGER tgNotNullYonMyTable
ON my_table
FOR UPDATE
AS
IF UPDATE(y)
BEGIN
IF exists (
select 1
from deleted d
join inserted i on i.id = d.id
where (d.x is null or i.x is null)
and i.y is null
)
BEGIN
RAISERROR ('Leave Y alone if x is null.', 16, 1)
rollback tran
END
END
go
insert my_table values (null,null)
go
update my_table set y = 'blah' where id = 1;
go
update my_table set y = null where id = 1;
CREATE TRIGGER yxnull
ON mytable
FOR UPDATE
AS
IF UPDATE(y)
BEGIN
IF deleted.x is null and inserted.y is not null
BEGIN
RAISERROR ('Leave Y alone if x is null.', 16, 1)
ROLLBACK TRANSACTION
END
END
go