SQL Change in one table automatically change the other table - sql-server

I am new to Database and in SQL also. I have two tables t1 and t2. There is a "name" column in t1 and t2 tables. Here t1. name will be given by me, but I want that t2. name automatically change on the basis of t1. id=t2. id please help me by giving SQL query for it. Also tells me "is, stored procedures or triggers required for this?" If yes, then how I will use them? Thanks in advance..... :-)

CREATE TRIGGER [dbo].[trg_Table2]
ON [dbo].[table1] AFTER UPDATE
AS
BEGIN
IF UPDATE (name)
BEGIN
INSERT INTO table2 (name)
SELECT d.name FROM DELETED d
END
END
I provided you an idea. Use it for updating the record. Here 'Deleted' table is the one where the data changed in table1 which can be used to store that previous data into other table that you want. I inserted the data, you update it now.
Sorry, I just saw it, you want the current data then use the 'INSERTED' table just like the 'DELETED'.

Related

SQL Server trigger to change NULL to empty strings

I'm migrating an Access database to a SQL Server 2014 Express back end and the application as it is is designed to put empty strings in some columns in some of the tables instead of NULL's (Access's behavior on attached forms).
It turns out I can't have the table not allow nulls in these columns because when attached to a bound form via ODBC attached tables Access explicitly is trying to insert NULL values when someone simply deletes the contents of a column, even if I have a default value defined on the table.
I want to say up front that I will be fixing this to handle NULLs properly, but for 'right now', my priority is to just get the back end converted to SQL operating the same as it was in Access, so I just want a trigger to change NULL values on a few fields to empty strings until such a time when I can look at all the application logic which is expecting empty strings in these fields right now and change it to handle NULLs.
I came up with the following:
CREATE TRIGGER TABLE1_ReplaceNulls
ON TABLE1
AFTER INSERT, UPDATE
AS
IF UPDATE(FIELDWNULL1)
BEGIN
UPDATE TABLE1
SET FIELDWNULL1 = ''
FROM inserted I
INNER JOIN TABLE1 ON I.PKFIELD = TABLE1.PKFIELD
WHERE I.FIELDWNULL1 IS NULL;
END;
This works fine for a single column. How best do I do this for multiple columns in the same table? I have one table with 4 columns that all could contain NULLS, but I want empty strings in place of them.
Should I do a separate IF block for each column that could contain the NULL or just handle it all at once? Of course, if I handle it all at once I would have to consider some of the columns might have legit values, but if I do separate statements then it could essentially run 4 updates after a column is inserted. Maybe it doesn't matter as this is all temporary, but just curious on other more experienced thoughts.
Using below update statement,update all four column in one trans. This code is not tested.
UPDATE TABLE1
SET FIELDWNULL1=iif(FIELDWNULL1 is null,'',FIELDWNULL1),
FIELDWNULL2=iif(FIELDWNULL2 is null,'',FIELDWNULL2),
FIELDWNULL3=iif(FIELDWNULL3 is null,'',FIELDWNULL3),
FIELDWNULL4=iif(FIELDWNULL4 is null,'',FIELDWNULL4)
FROM inserted I INNER JOIN TABLE1
ON I.PKFIELD = TABLE1.PKFIELD
New trigger code: With IIF statement
CREATE TRIGGER TABLE1_ReplaceNulls ON TABLE1
AFTER INSERT, UPDATE
AS
--IF UPDATE(FIELDWNULL1)
BEGIN
UPDATE TABLE1
SET FIELDWNULL1=iif(FIELDWNULL1 is null,'',FIELDWNULL1),
FIELDWNULL2=iif(FIELDWNULL2 is null,'',FIELDWNULL2),
FIELDWNULL3=iif(FIELDWNULL3 is null,'',FIELDWNULL3),
FIELDWNULL4=iif(FIELDWNULL4 is null,'',FIELDWNULL4)
FROM inserted I INNER JOIN TABLE1
ON I.PKFIELD = TABLE1.PKFIELD
--WHERE I.FIELDWNULL1 IS NULL;
END;
With ISNULL() function
CREATE TRIGGER TABLE1_ReplaceNulls ON TABLE1
AFTER INSERT, UPDATE
AS
--IF UPDATE(FIELDWNULL1)
BEGIN
UPDATE TABLE1
SET FIELDWNULL1=ISNULL(FIELDWNULL1,''),
FIELDWNULL2=ISNULL(FIELDWNULL2,''),
FIELDWNULL3=ISNULL(FIELDWNULL3,''),
FIELDWNULL4=ISNULL(FIELDWNULL4,'')
FROM inserted I INNER JOIN TABLE1
ON I.PKFIELD = TABLE1.PKFIELD
--WHERE I.FIELDWNULL1 IS NULL;
END;

Adding modify and delete to insert trigger

I've been tasked with pushing records from one table (T1) to another (T2). I have the insert portion complete as follows:
CREATE TRIGGER [dbo].[CP_to_TW2]
ON [dbo].[TEST_PROJ]
FOR INSERT
AS
BEGIN
INSERT INTO dbo.TEST_TW (PROJECT_ID,PROJECT_DESC,PROJECT_MANAGER)
SELECT PROJ_ID,PROJ_ID+PROJ_NAME,PROJECT_MANAGER FROM inserted
END
TEST_PROJ is T1 and TEST_TW is T2. The PROJECT_ID and PROJ_ID columns store the unique IDs. The trigger fires correct and inserts corresponding rows into T2. However, I am unsure how to get modifications made to T1 to show in T2. For example, if the Project manager is updated in T1 it needs to also update in T2. In addition to this, I am unsure how to make that records in T2 are deleted when they are deleted in T1. Any help would be greatly appreciated.
You can create triggers also for delete or update ops, in update you have deleted table in addition to inserted
CREATE TRIGGER [dbo].[CP_to_TW2]
ON [dbo].[TEST_PROJ]
AFTER UPDATE
AS
BEGIN
UPDATE TEST_TW....
END
CREATE TRIGGER [dbo].[CP_to_TW2]
ON [dbo].[TEST_PROJ]
AFTER DELETE
AS
BEGIN
DELETE FROM dbo.TEST_TW (PROJECT_ID,PROJECT_DESC,PROJECT_MANAGER)
WHERE xxx in (SELECT xxx FROM deleted)
END

Unique entries over to tables in database

I have a problem where I need to check that two columns in each table in a database are unique.
We have the database with barcode entries called uid and rid.
Table 1: T1.uid
And
Table 2: T2.rid
No barcodes in the two table columns must be the same.
How can we ensure that.
If a insertion of a barcode into table T1.uid matches an entry in
T2.rid we want to throw an error.
The tables are cleaned up and is in a consistent state where the entries in
T1.uid and T2.rid are unique over both table columns.
It is not possible to insert NULL values in the tables respective uid and tid column(T1.uid and T2.rid)
It is not possible to create a new table for all barcodes.
Because we don't have full control of the database server.
EDIT 19-02-2015
This solution cannot work for us, because we cannot make a new table
to keep track of the unique names(see table illustration).
We want to have a constraint over two columns in different tables without changing the schema.
Per the illustration we want to make it impossible for john to exist in
T2 because he already exists in table T1. So an error must be "thrown"
when we try to insert John in T2.Name.
The reason is that we have different suppliers that inserts into these tables
in different ways, if we change the schema layout, all suppliers would
need to change their database queries. The total work is just to much,
if we force every suppplier to make changes.
So we need something unobtrusive, that doesnt require the suppliers to change
their code.
A example could be that T1.Name is unique and do not accept NULL values.
If we try insert an existing name, like "Alan", then an exception will occur
because the column has unique values.
But we want to check for uniqueness in T2.Name at the same time.
The new inserted value should be unique over the two tables.
Maybe something like this:
SELECT uid FROM Table1
Where Exists (
SELECT rid FROM Table2
WHERE Table1.uid = rid )
This will show all rows from Table1 where their column uid has an equivalent in column rid of Table2.
The condition before the insertion happens could look like below. #Idis the id you need to insert the data for.
DECLARE #allowed INT;
SELECT #allowed = COUNT(*)
FROM
(
SELECT T1.uid FROM T1 WHERE T1.uid = #Id
UNION ALL
SELECT T2.rid FROM T2 WHERE T2.rid = #id
)
WHERE
#id IS NOT NULL;
IF #allowed = 0
BEGIN
---- insert allowed
SELECT 0;
END
Thanks to all who answered.
I have solved the problem. A trigger is added to the database
everytime an insert or update procedure is executed, we catch it
check that the value(s) to be inserted doens't exist in the columns of the two
tables. if that check is succesfull we exceute the original query.
Otherwise we rollback the query.
http://www.codeproject.com/Articles/25600/Triggers-SQL-Server
Instead Of Triggers

how to update table(new_DB) from old table(old_DB)

What I have:
1 table(table is in both DB's)
2 databases(currently used + archived from last year(old))
"ID" is the primary key for the table.
my issue:
archived database table has rows in it that is not present in the currently used database table. Can anyone tell me how I go about updating the currently used database table from the old database table(i.e. insert * unique rows from old database table into new database table)
It sounds simple enough but wanted some advice before proceeding as I DO NOT want duplicate rows, I just want to throw the rows in the old table(that IS NOT present in the currently used database table) into the new one(copy only is fine).
I hope I explained clearly enough.
Insert rows from the new table only if row with same id not exists in old table:
insert into old_table select * from new_table nt
where not exists (select 1 from old_table
where id = nt.id)
(Specifying columns, both inserted and selected, is nice - but I'm lazy here...)
You can usually address tables from other databases by prefixing the database name: new_db.foo_table or old_db.foo_table. This way you can look for rows in the old table that have no duplicates in the new table:
select *
from old_db.foo_table as old_foo
where not exists (
select 1
from new_db.foo_table as new_foo
where new_foo.key_field = old_foo.key_field
-- add more comparisons as needed
);
Then you can use the insert into new_db.foo_table select ... syntax to put the records into the new table.
Use LEFT JOIN filtering NULLs in target table. I think it will be faster
INSERT INTO NEW_TABLE
SELECT ot.* FROM OLD_TABLE ot
LEFT JOIN NEW_TABLE nt on ot.ID = nt.ID
WHERE nt.ID IS NULL

What is the best way to figure out if an UPDATE, DELETE or INSERT occur for a trigger

I want to create a single trigger in MS SQL for INSERT, UPDATE and DELETE but I want to be able to simple extract the data without 3 IF statements
I want to do something like this:
DECLARE #PK int
SELECT #PK = COALESCE(i.PK, d.PK)
FROM inserted i, deleted d
This did not work but would like to know if I can do it in one query.
What are some alternatives?
You can do the switch logic found here: SQL Server Trigger switching Insert,Delete,Update
Or you can create 3 different triggers.
Those are you options.
I ended up using a FULL OUTER JOIN
DECLARE #DataIWanted as varchar(255)
SELECT #DataIWanted = COALESCE(i.TheData,d.TheData)
FROM inserted i
FULL OUTER JOIN deleted d on d.PK=i.PK
The query above will be from the deleted table or the inserted/updated table. With the assumption that TheData is defined as NON NULL in the DB.

Resources