In SQL Server when I execute these two commands together
INSERT INTO TABLEB SELECT * FROM TABLEC WHERE TABLEC.COLUMNC = 'ABC'
DELETE TABLEC where TABLEC.columnC = 'ABC'
I only get the delete result. Insert did return a message saying x row affected but the content in the table remains empty.
Actual code
INSERT INTO STORECODE_BK SELECT * FROM STORE WHERE STOREID = '334'
DELETE STORE where STOREID = '334'
geomagas Had gotten the solution
Is due to the ON DELETE CASCADE attribute which delete the relevant PK
Thanks
Try the following.
INSERT INTO STORECODE_BK SELECT * FROM STORE WHERE STOREID = '334'
GO
DELETE FROM STORE where STOREID = '334'
GO
Select into a temporary table.
Then use that to insert into TableB and maybe delete from Table C
Then select from the temporary table.
Got to say all the hoops you are having to jump through indicates a less than great design.
Related
I have two SQL Server tables called Table A and Table B. I have an application which inserts one row into Table A and three rows into Table B at the same time. As you can see in the screenshot below, we can link these inserted records based on their ID column in Table A and TransID column in Table B.
During the data insert on table B, if any rows out of 3 inserted rows contain a value called Printed in the Printed column, I want to update my Table A's relevant record's PrintStatus column to Printed as well.
How do I write a SQL Server trigger for this?
Well the best solution is to do this in your code(app) but if there is no way,
you can write a Trigger After Insert for Table B like the trigger example below:
CREATE TRIGGER [dbo].[YourTrigger] ON [dbo].[TableB]
AFTER INSERT
AS
DECLARE #id INT
BEGIN
SET NOCOUNT ON;
SET #id = (SELECT DISTINCT ID FROM Inserted)
IF EXISTS (SELECT * FROM Inserted WHERE Printed='Printed')
UPDATE TableA
SET PrintStatus='Printed'
WHERE ID = #id
END
May this help you
It could be correct for your problem : (not sure at 100%)
CREATE TRIGGER TriggerTableB
ON TableB
AFTER INSERT
AS
UPDATE TableA AS A
SET PrintStatus = 'Printed'
WHERE A.TranID = inserted.ID
AND 'Printed' = (SELECT MAX(I.Printed)
FROM inserted AS I)
I would recommend querying for the information:
select a.*,
(case when exists (select 1
from b
where b.id = a.tranid and b.printed = 'Printed'
)
then 'Printed'
end) as printstatus
from a;
This is simpler than writing a query and you can wrap this in a view.
From a performance perspective, an index on b(id, printed) should make this pretty fast -- and not slow down inserts.
A trigger can be quite complicated, if you want to take inserts, updates, and deletes into account. I prefer to avoid such complication, if possible.
I'm trying to do a job that will copy data from a foreign table called "m_aduana" of the schema "nathalia" to my schema "publico" and my table "mae_aduana".
I need to do a query that copies all the values from the table "m_aduana" avoiding duplicates.
I got something like this for now but the result sends me an Insert 0 0, which means nothing is inserted.
insert into publico.mae_aduana(cod_aduana,nom_aduana,des_aduana,cod_aduana1,cod_aduana2,cod_aduana3,est_aduana)
select cod_aduana,nom_aduana,des_aduana,cod_aduana1,cod_aduana2,cod_aduana3,est_aduana
from nathalia.m_aduana
where not exists (
select * from publico.mae_aduana ma_ad, nathalia.m_aduana m_ad
where ma_ad.cod_aduana = m_ad.cod_aduana)
I think you have an error in the inner select. You don't need to use again the table nathalia.m_aduana. If should be something like:
insert into publico.mae_aduana(cod_aduana,nom_aduana,des_aduana,cod_aduana1,cod_aduana2,cod_aduana3,est_aduana)
select cod_aduana,nom_aduana,des_aduana,cod_aduana1,cod_aduana2,cod_aduana3,est_aduana
from nathalia.m_aduana
where not exists (
select * from publico.mae_aduana ma_ad
where ma_ad.cod_aduana = nathalia.m_aduana.cod_aduana)
You might want to change the where exists part like below
from nathalia.m_aduana m
where not exists (
select 1 from publico.mae_aduana
where cod_aduana = m.cod_aduana)
I need to select entire columns from table compression_query_table into Tenth_mile but INSERT deletes columns already in that Table that aren't in Compression_query_Table and I cannot figure out how to use UPDATE on multiple columns at the same time.
Considering your session_name is unique, you could probably write two separate statements: INSERT and UPDATE for this:
Update Statement:
UPDATE Tenth_mile
INNER JOIN compression_query_table cq on Tenth_mile.session_name = cq.session_name
SET Tenth_mile.State = cq.State,
Tenth_mile.route_number = cq.route_number;
Insert Statement:
INSERT INTO Tenth_mile (session_name, state, route_number)
SELECT session_name
,STATE
,route_number
FROM compression_query_table cq
WHERE NOT EXISTS
(SELECT tm.session_name
FROM Tenth_Mile tm
WHERE tm.session_name = cq.session_name
);
Note: I don't have MS-Access installed on my machine, so I don't have
a way to test this. Also, I would run the update before running the insert statement (aka upsert).
Hope this helps!
Icurrently have in my database (SQL server 2005 Express) 2 tables, tblDepartment and tblDepartmentcola. The difference between the two is that "cola" has an additional boolean field. For reasons beyond the scope of this question, i need to insert any changes made to tblDepartment in tblDepartmentcola. For that i need to use a trigger.
After reading some stuff, i got the impression that a temporary "updated" table does not exist? is this right?. If so, how could i select the "updated" row?, i have made triggers in the past making selects from "updated" and "Deleted" tables, but this one does not work. any idea why?
CREATE TRIGGER items_ ON [tblDepartment] FOR Update AS
INSERT INTO [tblDepartmentcola]
SELECT ...
go
there's no updated table in Sql server, only inserted and deleted
CREATE TRIGGER items_ ON [tblDepartment] after Update AS
begin
INSERT INTO [tblDepartmentcola]
SELECT * from inserted
end
If you want to see the records that were updated to insert into a different table you can query the INSERTED table within a trigger when the primary key exists within the DELETED table.
INSERT INTO TrackUpdatesTable ( PrimaryFieldId, Field1, Field2, Field3 )
SELECT I.PrimaryFieldId, I.Field1, I.Field2, I.Field3
FROM INSERTED I
JOIN DELETED D ON D.PrimaryFieldId = I.PrimaryFieldId
or
INSERT INTO TrackUpdatesTable ( PrimaryFieldId, Field1, Field2, Field3 )
SELECT I.PrimaryFieldId, I.Field1, I.Field2, I.Field3
FROM INSERTED I
WHERE EXISTS ( SELECT * FROM DELETED WHERE PrimaryFieldId = I.PrimaryFieldId )
Hope this helps.
I'm trying to verify a simple 1 field table to determine if a record exists before inserting a duplicate.
if not exists (select * from url where url = ...)
insert into url...
Can someone Help?
Your code example will run in the full version of SQL, or you could rearrange to the following:
insert into url
select 'myvalue'
where not exists (select * from url where url = 'myvalue')
Just reverse it and add the condition as a where clause predicate
Insert Into Table ....
Where Not Exists
(Select * From table where ...)
... But your basic problem sounds like it might be better solved by putting a alternate key (unique) constraint on the insert table, referencing the url column (I assume Sql CE does Referential Integrity (RI) constraints?)
You might want to read this thread. performing-insert-or-update-upsert-on-sql-server-compact-edition
In a nutshell a sqlce specific solution (using SqlCeResultSet) will provide the maximum performance.
Use an Outer Join
Insert into X(...)
select blah, blah, blah
from
table t left outer join
X on t.id=x.id
where
x.id is null
Granted, this is way past the posting date, but since I've not seen this answered elsewhere in my quick Google search, I thought I'd share how I solved this with SQL CE so others searching might find an answer.
-- Update existing record's value
UPDATE myTable SET myValue = 'Hello World' WHERE keyField = 'MyKey';
-- Insert new record if existing record doesn't exist`
INSERT INTO myTable (keyField, myValue)
SELECT I.keyField, I.myValue
FROM (
SELECT 'Hello World' AS myValue, 'MyKey' AS keyField
) I
LEFT JOIN myTable T ON I.keyField = T.keyField
WHERE T.keyField IS NULL;
You are on the right path with IF NOT EXISTS. It is better to use IF NOT EXISTS() or IF EXISTS() than a Sub Query because SQL Server will stop scanning rows in the table when it finds the first instance that matches the EXISTS() condition your looking for. With a Sub Query written in the examples above it will scan the whole table.
A Classic example is the Insert or Update aka the SAVE.
IF EXISTS(SELECT * FROM Table_A WHERE Column_1 = #Parameter)
BEGIN
--Update Statement here.
END
ELSE
BEGIN
--Insert Statement here.
END
What about something like this:
UPDATE Table1 SET (...) WHERE Column1='SomeValue'
IF ##ROWCOUNT=0
INSERT INTO Table1 VALUES (...)
Source