Hello,
I need to write a trigger that removes repeated elements on a table.
I want to delete every row where the field "name" has beenrepeated.
Any hel in writing such a trigger would be so much higly appreciated.
Many thinks in advance
JBWhy do this via a trigger? Wouldn't it be easier to not insert duplicate
rows to begin with?
Adam Machanic
SQL Server MVP
http://www.sqljunkies.com/weblog/amachanic
--
"Jensen bredal" <jensen.bredahl@.yahoo.com> wrote in message
news:O9xhu5PHFHA.3624@.tk2msftngp13.phx.gbl...
> Hello,
> I need to write a trigger that removes repeated elements on a table.
> I want to delete every row where the field "name" has beenrepeated.
> Any hel in writing such a trigger would be so much higly appreciated.
> Many thinks in advance
> JB
>|||While this is a very good question, it appears that we
need the other option.
We are doing something very unusual. This is a system
integration project and we are sharing this database with other systems.
I won''t go in furthere details and hope that make sens.
Many thanks
JB|||You could try an INSTEAD OF trigger:
CREATE TRIGGER TG_NoDupes
ON YourTable
FOR INSERT
AS
BEGIN
IF @.@.ROWCOUNT = 0
RETURN
INSERT YourTable
SELECT *
FROM INSERTED
WHERE NOT EXISTS
(SELECT *
FROM YourTable
WHERE YourTable.Name = INSERTED.Name)
END
Adam Machanic
SQL Server MVP
http://www.sqljunkies.com/weblog/amachanic
--
"Jensen bredal" <jensen.bredahl@.yahoo.com> wrote in message
news:%23SifbHQHFHA.1176@.TK2MSFTNGP12.phx.gbl...
> While this is a very good question, it appears that we
> need the other option.
> We are doing something very unusual. This is a system
> integration project and we are sharing this database with other systems.
> I won''t go in furthere details and hope that make sens.
> Many thanks
> JB
>|||Jensen,
Unless I'm really not understanding, what you are asking for is inherently
inconsistent. Either you want a PROCEDURE that will delete all instances
where name has been repeated, or you want a TRIGGER to PREVENT the insert of
such records in the first place. An insert TRIGGER, for eg, will fire and
run EVERY TIME a record is inserted. If you wrote it to delete all existing
duplicates, it would be re-running that code over and over- again
unnecessarily, on every insert, when the first run would have already delete
d
all existing duplicates.
What it sounds like yuou might actually need, (excuse me if I've
mistunderastood) is a procedure to run ONCE to delete all existing
duplicates, and a trigger, (actually a unique constraint on the name Column
would do it) that would prevent furthur inserts of duplicates in the future.
Anyway, if so, for the first step, to eliminate existing dupes, sasuming the
table has a Primary Key, called say "PKID", try this:
Delete T
From TableName T
Where Name In (Select Name From TableName
Group By Name
Having Count(*) > 1)
And PKID <> (Select Min(PKID)
From TableName
Where Name = T.Name)
"Jensen bredal" wrote:
> Hello,
> I need to write a trigger that removes repeated elements on a table.
> I want to delete every row where the field "name" has beenrepeated.
> Any hel in writing such a trigger would be so much higly appreciated.
> Many thinks in advance
> JB
>
>|||"Jensen bredal" <jensen.bredahl@.yahoo.com> wrote in message
news:O9xhu5PHFHA.3624@.tk2msftngp13.phx.gbl...
> Hello,
> I need to write a trigger that removes repeated elements on a table.
> I want to delete every row where the field "name" has beenrepeated.
> Any hel in writing such a trigger would be so much higly
appreciated.
> Many thinks in advance
> JB
>
Jensen bredal,
May I ask why you are operating a table without a Primary Key? (Yes,
I did read the other portion of the thread where the "We're doing
something unusual" answer was given, but I'm still curious).
From the description, it sounds like you want to keep out duplicate
records. This is the effect a Primary Key has, and it's a lot faster
than any trigger.
Sincerely,
Chris O.|||Well as i said this is not the every day scenario.
I may give you a full explaination if you have time to read my answer. Let
me know if you want that.
JB
"Chris2" <rainofsteel.NOTVALID@.GETRIDOF.luminousrain.com> wrote in message
news:MPednYwUXbNt_r_fRVn-sA@.comcast.com...
> "Jensen bredal" <jensen.bredahl@.yahoo.com> wrote in message
> news:O9xhu5PHFHA.3624@.tk2msftngp13.phx.gbl...
> appreciated.
> Jensen bredal,
> May I ask why you are operating a table without a Primary Key? (Yes,
> I did read the other portion of the thread where the "We're doing
> something unusual" answer was given, but I'm still curious).
> From the description, it sounds like you want to keep out duplicate
> records. This is the effect a Primary Key has, and it's a lot faster
> than any trigger.
>
> Sincerely,
> Chris O.
>
Showing posts with label trigger. Show all posts
Showing posts with label trigger. Show all posts
Monday, March 19, 2012
Wednesday, March 7, 2012
Newbie : How to make Trigger for inserting/updating fields?
Hi All,
I have fields ModifyID, ModifyTime, UpdateID, UpdateTime which I update from
application, however since I new to SQLServer (used to use Access) I want to
insert/update these fields via trigger, the ModifyID should contain the user
name logged on to the SQLServer and the time he modify or insert the row.
Could this two insert/update containing in one trigger? Any help would be
highly appreciated. TIA.
HendrickCREATE TRIGGER YourTriggerName
ON YourTable
FOR INSERT, UPDATE
AS
BEGIN
UPDATE YourTable
SET
UpdateTime = GETDATE(),
UpdateID = USER_ID()
WHERE YourTable.PK IN
(
SELECT PK
FROM INSERTED
)
END
... Replace 'PK' with the primary key column(s) from your table.
Adam Machanic
SQL Server MVP
http://www.datamanipulation.net
--
"Hendrick" <hbouty@.not.gmail.com> wrote in message
news:uZe0ITdzFHA.4032@.TK2MSFTNGP15.phx.gbl...
> Hi All,
> I have fields ModifyID, ModifyTime, UpdateID, UpdateTime which I update
> from
> application, however since I new to SQLServer (used to use Access) I want
> to
> insert/update these fields via trigger, the ModifyID should contain the
> user
> name logged on to the SQLServer and the time he modify or insert the row.
> Could this two insert/update containing in one trigger? Any help would be
> highly appreciated. TIA.
> Hendrick
>|||Great. Thanks for the prompt reply.
Hendrick
"Adam Machanic" <amachanic@.hotmail._removetoemail_.com> wrote in message
news:#VvKdYdzFHA.3124@.TK2MSFTNGP12.phx.gbl...
> CREATE TRIGGER YourTriggerName
> ON YourTable
> FOR INSERT, UPDATE
> AS
> BEGIN
> UPDATE YourTable
> SET
> UpdateTime = GETDATE(),
> UpdateID = USER_ID()
> WHERE YourTable.PK IN
> (
> SELECT PK
> FROM INSERTED
> )
> END
>
> ... Replace 'PK' with the primary key column(s) from your table.
>
> --
> Adam Machanic
> SQL Server MVP
> http://www.datamanipulation.net
> --
>
> "Hendrick" <hbouty@.not.gmail.com> wrote in message
> news:uZe0ITdzFHA.4032@.TK2MSFTNGP15.phx.gbl...
> > Hi All,
> >
> > I have fields ModifyID, ModifyTime, UpdateID, UpdateTime which I update
> > from
> > application, however since I new to SQLServer (used to use Access) I
want
> > to
> > insert/update these fields via trigger, the ModifyID should contain the
> > user
> > name logged on to the SQLServer and the time he modify or insert the
row.
> > Could this two insert/update containing in one trigger? Any help would
be
> > highly appreciated. TIA.
> >
> > Hendrick
> >
> >
>|||Hendrick,
Also see 'Multirow Considerations' in the SQL Server Books Online.
HTH
Jerry
"Hendrick" <hbouty@.not.gmail.com> wrote in message
news:O4b8RddzFHA.3408@.TK2MSFTNGP09.phx.gbl...
> Great. Thanks for the prompt reply.
> Hendrick
> "Adam Machanic" <amachanic@.hotmail._removetoemail_.com> wrote in message
> news:#VvKdYdzFHA.3124@.TK2MSFTNGP12.phx.gbl...
>> CREATE TRIGGER YourTriggerName
>> ON YourTable
>> FOR INSERT, UPDATE
>> AS
>> BEGIN
>> UPDATE YourTable
>> SET
>> UpdateTime = GETDATE(),
>> UpdateID = USER_ID()
>> WHERE YourTable.PK IN
>> (
>> SELECT PK
>> FROM INSERTED
>> )
>> END
>>
>> ... Replace 'PK' with the primary key column(s) from your table.
>>
>> --
>> Adam Machanic
>> SQL Server MVP
>> http://www.datamanipulation.net
>> --
>>
>> "Hendrick" <hbouty@.not.gmail.com> wrote in message
>> news:uZe0ITdzFHA.4032@.TK2MSFTNGP15.phx.gbl...
>> > Hi All,
>> >
>> > I have fields ModifyID, ModifyTime, UpdateID, UpdateTime which I update
>> > from
>> > application, however since I new to SQLServer (used to use Access) I
> want
>> > to
>> > insert/update these fields via trigger, the ModifyID should contain the
>> > user
>> > name logged on to the SQLServer and the time he modify or insert the
> row.
>> > Could this two insert/update containing in one trigger? Any help would
> be
>> > highly appreciated. TIA.
>> >
>> > Hendrick
>> >
>> >
>>
>|||Hey Jerry,
Did a search on Multirow Considerations in my book online, didn't get
anything back.
(SQL SERVER 2000 sp4). Do you have a more specific indication of what we
should be aware of here? Always wanna learn more ;-)
Thanks,
Bob
"Jerry Spivey" <jspivey@.vestas-awt.com> wrote in message
news:unJ3T5dzFHA.2884@.TK2MSFTNGP09.phx.gbl...
> Hendrick,
> Also see 'Multirow Considerations' in the SQL Server Books Online.
> HTH
> Jerry
> "Hendrick" <hbouty@.not.gmail.com> wrote in message
> news:O4b8RddzFHA.3408@.TK2MSFTNGP09.phx.gbl...
>> Great. Thanks for the prompt reply.
>> Hendrick
>> "Adam Machanic" <amachanic@.hotmail._removetoemail_.com> wrote in message
>> news:#VvKdYdzFHA.3124@.TK2MSFTNGP12.phx.gbl...
>> CREATE TRIGGER YourTriggerName
>> ON YourTable
>> FOR INSERT, UPDATE
>> AS
>> BEGIN
>> UPDATE YourTable
>> SET
>> UpdateTime = GETDATE(),
>> UpdateID = USER_ID()
>> WHERE YourTable.PK IN
>> (
>> SELECT PK
>> FROM INSERTED
>> )
>> END
>>
>> ... Replace 'PK' with the primary key column(s) from your table.
>>
>> --
>> Adam Machanic
>> SQL Server MVP
>> http://www.datamanipulation.net
>> --
>>
>> "Hendrick" <hbouty@.not.gmail.com> wrote in message
>> news:uZe0ITdzFHA.4032@.TK2MSFTNGP15.phx.gbl...
>> > Hi All,
>> >
>> > I have fields ModifyID, ModifyTime, UpdateID, UpdateTime which I
>> > update
>> > from
>> > application, however since I new to SQLServer (used to use Access) I
>> want
>> > to
>> > insert/update these fields via trigger, the ModifyID should contain
>> > the
>> > user
>> > name logged on to the SQLServer and the time he modify or insert the
>> row.
>> > Could this two insert/update containing in one trigger? Any help would
>> be
>> > highly appreciated. TIA.
>> >
>> > Hendrick
>> >
>> >
>>
>>
>|||Bob,
Here is the 2005 link http://msdn2.microsoft.com/en-us/library/ms250511.
Are you using the latest SQL Server Books Online? Here is the link to
upgrade if not:
http://www.microsoft.com/sql/techinfo/productdoc/2000/books.mspx
HTH
Jerry
"Bob" <bdufournosp@.sgiims.com> wrote in message
news:eWEpoEezFHA.3588@.tk2msftngp13.phx.gbl...
> Hey Jerry,
> Did a search on Multirow Considerations in my book online, didn't get
> anything back.
> (SQL SERVER 2000 sp4). Do you have a more specific indication of what we
> should be aware of here? Always wanna learn more ;-)
> Thanks,
> Bob
> "Jerry Spivey" <jspivey@.vestas-awt.com> wrote in message
> news:unJ3T5dzFHA.2884@.TK2MSFTNGP09.phx.gbl...
>> Hendrick,
>> Also see 'Multirow Considerations' in the SQL Server Books Online.
>> HTH
>> Jerry
>> "Hendrick" <hbouty@.not.gmail.com> wrote in message
>> news:O4b8RddzFHA.3408@.TK2MSFTNGP09.phx.gbl...
>> Great. Thanks for the prompt reply.
>> Hendrick
>> "Adam Machanic" <amachanic@.hotmail._removetoemail_.com> wrote in message
>> news:#VvKdYdzFHA.3124@.TK2MSFTNGP12.phx.gbl...
>> CREATE TRIGGER YourTriggerName
>> ON YourTable
>> FOR INSERT, UPDATE
>> AS
>> BEGIN
>> UPDATE YourTable
>> SET
>> UpdateTime = GETDATE(),
>> UpdateID = USER_ID()
>> WHERE YourTable.PK IN
>> (
>> SELECT PK
>> FROM INSERTED
>> )
>> END
>>
>> ... Replace 'PK' with the primary key column(s) from your table.
>>
>> --
>> Adam Machanic
>> SQL Server MVP
>> http://www.datamanipulation.net
>> --
>>
>> "Hendrick" <hbouty@.not.gmail.com> wrote in message
>> news:uZe0ITdzFHA.4032@.TK2MSFTNGP15.phx.gbl...
>> > Hi All,
>> >
>> > I have fields ModifyID, ModifyTime, UpdateID, UpdateTime which I
>> > update
>> > from
>> > application, however since I new to SQLServer (used to use Access) I
>> want
>> > to
>> > insert/update these fields via trigger, the ModifyID should contain
>> > the
>> > user
>> > name logged on to the SQLServer and the time he modify or insert the
>> row.
>> > Could this two insert/update containing in one trigger? Any help
>> > would
>> be
>> > highly appreciated. TIA.
>> >
>> > Hendrick
>> >
>> >
>>
>>
>>
>
I have fields ModifyID, ModifyTime, UpdateID, UpdateTime which I update from
application, however since I new to SQLServer (used to use Access) I want to
insert/update these fields via trigger, the ModifyID should contain the user
name logged on to the SQLServer and the time he modify or insert the row.
Could this two insert/update containing in one trigger? Any help would be
highly appreciated. TIA.
HendrickCREATE TRIGGER YourTriggerName
ON YourTable
FOR INSERT, UPDATE
AS
BEGIN
UPDATE YourTable
SET
UpdateTime = GETDATE(),
UpdateID = USER_ID()
WHERE YourTable.PK IN
(
SELECT PK
FROM INSERTED
)
END
... Replace 'PK' with the primary key column(s) from your table.
Adam Machanic
SQL Server MVP
http://www.datamanipulation.net
--
"Hendrick" <hbouty@.not.gmail.com> wrote in message
news:uZe0ITdzFHA.4032@.TK2MSFTNGP15.phx.gbl...
> Hi All,
> I have fields ModifyID, ModifyTime, UpdateID, UpdateTime which I update
> from
> application, however since I new to SQLServer (used to use Access) I want
> to
> insert/update these fields via trigger, the ModifyID should contain the
> user
> name logged on to the SQLServer and the time he modify or insert the row.
> Could this two insert/update containing in one trigger? Any help would be
> highly appreciated. TIA.
> Hendrick
>|||Great. Thanks for the prompt reply.
Hendrick
"Adam Machanic" <amachanic@.hotmail._removetoemail_.com> wrote in message
news:#VvKdYdzFHA.3124@.TK2MSFTNGP12.phx.gbl...
> CREATE TRIGGER YourTriggerName
> ON YourTable
> FOR INSERT, UPDATE
> AS
> BEGIN
> UPDATE YourTable
> SET
> UpdateTime = GETDATE(),
> UpdateID = USER_ID()
> WHERE YourTable.PK IN
> (
> SELECT PK
> FROM INSERTED
> )
> END
>
> ... Replace 'PK' with the primary key column(s) from your table.
>
> --
> Adam Machanic
> SQL Server MVP
> http://www.datamanipulation.net
> --
>
> "Hendrick" <hbouty@.not.gmail.com> wrote in message
> news:uZe0ITdzFHA.4032@.TK2MSFTNGP15.phx.gbl...
> > Hi All,
> >
> > I have fields ModifyID, ModifyTime, UpdateID, UpdateTime which I update
> > from
> > application, however since I new to SQLServer (used to use Access) I
want
> > to
> > insert/update these fields via trigger, the ModifyID should contain the
> > user
> > name logged on to the SQLServer and the time he modify or insert the
row.
> > Could this two insert/update containing in one trigger? Any help would
be
> > highly appreciated. TIA.
> >
> > Hendrick
> >
> >
>|||Hendrick,
Also see 'Multirow Considerations' in the SQL Server Books Online.
HTH
Jerry
"Hendrick" <hbouty@.not.gmail.com> wrote in message
news:O4b8RddzFHA.3408@.TK2MSFTNGP09.phx.gbl...
> Great. Thanks for the prompt reply.
> Hendrick
> "Adam Machanic" <amachanic@.hotmail._removetoemail_.com> wrote in message
> news:#VvKdYdzFHA.3124@.TK2MSFTNGP12.phx.gbl...
>> CREATE TRIGGER YourTriggerName
>> ON YourTable
>> FOR INSERT, UPDATE
>> AS
>> BEGIN
>> UPDATE YourTable
>> SET
>> UpdateTime = GETDATE(),
>> UpdateID = USER_ID()
>> WHERE YourTable.PK IN
>> (
>> SELECT PK
>> FROM INSERTED
>> )
>> END
>>
>> ... Replace 'PK' with the primary key column(s) from your table.
>>
>> --
>> Adam Machanic
>> SQL Server MVP
>> http://www.datamanipulation.net
>> --
>>
>> "Hendrick" <hbouty@.not.gmail.com> wrote in message
>> news:uZe0ITdzFHA.4032@.TK2MSFTNGP15.phx.gbl...
>> > Hi All,
>> >
>> > I have fields ModifyID, ModifyTime, UpdateID, UpdateTime which I update
>> > from
>> > application, however since I new to SQLServer (used to use Access) I
> want
>> > to
>> > insert/update these fields via trigger, the ModifyID should contain the
>> > user
>> > name logged on to the SQLServer and the time he modify or insert the
> row.
>> > Could this two insert/update containing in one trigger? Any help would
> be
>> > highly appreciated. TIA.
>> >
>> > Hendrick
>> >
>> >
>>
>|||Hey Jerry,
Did a search on Multirow Considerations in my book online, didn't get
anything back.
(SQL SERVER 2000 sp4). Do you have a more specific indication of what we
should be aware of here? Always wanna learn more ;-)
Thanks,
Bob
"Jerry Spivey" <jspivey@.vestas-awt.com> wrote in message
news:unJ3T5dzFHA.2884@.TK2MSFTNGP09.phx.gbl...
> Hendrick,
> Also see 'Multirow Considerations' in the SQL Server Books Online.
> HTH
> Jerry
> "Hendrick" <hbouty@.not.gmail.com> wrote in message
> news:O4b8RddzFHA.3408@.TK2MSFTNGP09.phx.gbl...
>> Great. Thanks for the prompt reply.
>> Hendrick
>> "Adam Machanic" <amachanic@.hotmail._removetoemail_.com> wrote in message
>> news:#VvKdYdzFHA.3124@.TK2MSFTNGP12.phx.gbl...
>> CREATE TRIGGER YourTriggerName
>> ON YourTable
>> FOR INSERT, UPDATE
>> AS
>> BEGIN
>> UPDATE YourTable
>> SET
>> UpdateTime = GETDATE(),
>> UpdateID = USER_ID()
>> WHERE YourTable.PK IN
>> (
>> SELECT PK
>> FROM INSERTED
>> )
>> END
>>
>> ... Replace 'PK' with the primary key column(s) from your table.
>>
>> --
>> Adam Machanic
>> SQL Server MVP
>> http://www.datamanipulation.net
>> --
>>
>> "Hendrick" <hbouty@.not.gmail.com> wrote in message
>> news:uZe0ITdzFHA.4032@.TK2MSFTNGP15.phx.gbl...
>> > Hi All,
>> >
>> > I have fields ModifyID, ModifyTime, UpdateID, UpdateTime which I
>> > update
>> > from
>> > application, however since I new to SQLServer (used to use Access) I
>> want
>> > to
>> > insert/update these fields via trigger, the ModifyID should contain
>> > the
>> > user
>> > name logged on to the SQLServer and the time he modify or insert the
>> row.
>> > Could this two insert/update containing in one trigger? Any help would
>> be
>> > highly appreciated. TIA.
>> >
>> > Hendrick
>> >
>> >
>>
>>
>|||Bob,
Here is the 2005 link http://msdn2.microsoft.com/en-us/library/ms250511.
Are you using the latest SQL Server Books Online? Here is the link to
upgrade if not:
http://www.microsoft.com/sql/techinfo/productdoc/2000/books.mspx
HTH
Jerry
"Bob" <bdufournosp@.sgiims.com> wrote in message
news:eWEpoEezFHA.3588@.tk2msftngp13.phx.gbl...
> Hey Jerry,
> Did a search on Multirow Considerations in my book online, didn't get
> anything back.
> (SQL SERVER 2000 sp4). Do you have a more specific indication of what we
> should be aware of here? Always wanna learn more ;-)
> Thanks,
> Bob
> "Jerry Spivey" <jspivey@.vestas-awt.com> wrote in message
> news:unJ3T5dzFHA.2884@.TK2MSFTNGP09.phx.gbl...
>> Hendrick,
>> Also see 'Multirow Considerations' in the SQL Server Books Online.
>> HTH
>> Jerry
>> "Hendrick" <hbouty@.not.gmail.com> wrote in message
>> news:O4b8RddzFHA.3408@.TK2MSFTNGP09.phx.gbl...
>> Great. Thanks for the prompt reply.
>> Hendrick
>> "Adam Machanic" <amachanic@.hotmail._removetoemail_.com> wrote in message
>> news:#VvKdYdzFHA.3124@.TK2MSFTNGP12.phx.gbl...
>> CREATE TRIGGER YourTriggerName
>> ON YourTable
>> FOR INSERT, UPDATE
>> AS
>> BEGIN
>> UPDATE YourTable
>> SET
>> UpdateTime = GETDATE(),
>> UpdateID = USER_ID()
>> WHERE YourTable.PK IN
>> (
>> SELECT PK
>> FROM INSERTED
>> )
>> END
>>
>> ... Replace 'PK' with the primary key column(s) from your table.
>>
>> --
>> Adam Machanic
>> SQL Server MVP
>> http://www.datamanipulation.net
>> --
>>
>> "Hendrick" <hbouty@.not.gmail.com> wrote in message
>> news:uZe0ITdzFHA.4032@.TK2MSFTNGP15.phx.gbl...
>> > Hi All,
>> >
>> > I have fields ModifyID, ModifyTime, UpdateID, UpdateTime which I
>> > update
>> > from
>> > application, however since I new to SQLServer (used to use Access) I
>> want
>> > to
>> > insert/update these fields via trigger, the ModifyID should contain
>> > the
>> > user
>> > name logged on to the SQLServer and the time he modify or insert the
>> row.
>> > Could this two insert/update containing in one trigger? Any help
>> > would
>> be
>> > highly appreciated. TIA.
>> >
>> > Hendrick
>> >
>> >
>>
>>
>>
>
Newbie : How to make Trigger for inserting/updating fields?
Hi All,
I have fields ModifyID, ModifyTime, UpdateID, UpdateTime which I update from
application, however since I new to SQLServer (used to use Access) I want to
insert/update these fields via trigger, the ModifyID should contain the user
name logged on to the SQLServer and the time he modify or insert the row.
Could this two insert/update containing in one trigger? Any help would be
highly appreciated. TIA.
HendrickCREATE TRIGGER YourTriggerName
ON YourTable
FOR INSERT, UPDATE
AS
BEGIN
UPDATE YourTable
SET
UpdateTime = GETDATE(),
UpdateID = USER_ID()
WHERE YourTable.PK IN
(
SELECT PK
FROM INSERTED
)
END
... Replace 'PK' with the primary key column(s) from your table.
Adam Machanic
SQL Server MVP
http://www.datamanipulation.net
--
"Hendrick" <hbouty@.not.gmail.com> wrote in message
news:uZe0ITdzFHA.4032@.TK2MSFTNGP15.phx.gbl...
> Hi All,
> I have fields ModifyID, ModifyTime, UpdateID, UpdateTime which I update
> from
> application, however since I new to SQLServer (used to use Access) I want
> to
> insert/update these fields via trigger, the ModifyID should contain the
> user
> name logged on to the SQLServer and the time he modify or insert the row.
> Could this two insert/update containing in one trigger? Any help would be
> highly appreciated. TIA.
> Hendrick
>|||Great. Thanks for the prompt reply.
Hendrick
"Adam Machanic" <amachanic@.hotmail._removetoemail_.com> wrote in message
news:#VvKdYdzFHA.3124@.TK2MSFTNGP12.phx.gbl...
> CREATE TRIGGER YourTriggerName
> ON YourTable
> FOR INSERT, UPDATE
> AS
> BEGIN
> UPDATE YourTable
> SET
> UpdateTime = GETDATE(),
> UpdateID = USER_ID()
> WHERE YourTable.PK IN
> (
> SELECT PK
> FROM INSERTED
> )
> END
>
> ... Replace 'PK' with the primary key column(s) from your table.
>
> --
> Adam Machanic
> SQL Server MVP
> http://www.datamanipulation.net
> --
>
> "Hendrick" <hbouty@.not.gmail.com> wrote in message
> news:uZe0ITdzFHA.4032@.TK2MSFTNGP15.phx.gbl...
want[vbcol=seagreen]
row.[vbcol=seagreen]
be[vbcol=seagreen]
>|||Hendrick,
Also see 'Multirow Considerations' in the SQL Server Books Online.
HTH
Jerry
"Hendrick" <hbouty@.not.gmail.com> wrote in message
news:O4b8RddzFHA.3408@.TK2MSFTNGP09.phx.gbl...
> Great. Thanks for the prompt reply.
> Hendrick
> "Adam Machanic" <amachanic@.hotmail._removetoemail_.com> wrote in message
> news:#VvKdYdzFHA.3124@.TK2MSFTNGP12.phx.gbl...
> want
> row.
> be
>|||Hey Jerry,
Did a search on Multirow Considerations in my book online, didn't get
anything back.
(SQL SERVER 2000 sp4). Do you have a more specific indication of what we
should be aware of here? Always wanna learn more ;-)
Thanks,
Bob
"Jerry Spivey" <jspivey@.vestas-awt.com> wrote in message
news:unJ3T5dzFHA.2884@.TK2MSFTNGP09.phx.gbl...
> Hendrick,
> Also see 'Multirow Considerations' in the SQL Server Books Online.
> HTH
> Jerry
> "Hendrick" <hbouty@.not.gmail.com> wrote in message
> news:O4b8RddzFHA.3408@.TK2MSFTNGP09.phx.gbl...
>|||Bob,
Here is the 2005 link http://msdn2.microsoft.com/en-us/library/ms250511.
Are you using the latest SQL Server Books Online? Here is the link to
upgrade if not:
http://www.microsoft.com/sql/techin...2000/books.mspx
HTH
Jerry
"Bob" <bdufournosp@.sgiims.com> wrote in message
news:eWEpoEezFHA.3588@.tk2msftngp13.phx.gbl...
> Hey Jerry,
> Did a search on Multirow Considerations in my book online, didn't get
> anything back.
> (SQL SERVER 2000 sp4). Do you have a more specific indication of what we
> should be aware of here? Always wanna learn more ;-)
> Thanks,
> Bob
> "Jerry Spivey" <jspivey@.vestas-awt.com> wrote in message
> news:unJ3T5dzFHA.2884@.TK2MSFTNGP09.phx.gbl...
>
I have fields ModifyID, ModifyTime, UpdateID, UpdateTime which I update from
application, however since I new to SQLServer (used to use Access) I want to
insert/update these fields via trigger, the ModifyID should contain the user
name logged on to the SQLServer and the time he modify or insert the row.
Could this two insert/update containing in one trigger? Any help would be
highly appreciated. TIA.
HendrickCREATE TRIGGER YourTriggerName
ON YourTable
FOR INSERT, UPDATE
AS
BEGIN
UPDATE YourTable
SET
UpdateTime = GETDATE(),
UpdateID = USER_ID()
WHERE YourTable.PK IN
(
SELECT PK
FROM INSERTED
)
END
... Replace 'PK' with the primary key column(s) from your table.
Adam Machanic
SQL Server MVP
http://www.datamanipulation.net
--
"Hendrick" <hbouty@.not.gmail.com> wrote in message
news:uZe0ITdzFHA.4032@.TK2MSFTNGP15.phx.gbl...
> Hi All,
> I have fields ModifyID, ModifyTime, UpdateID, UpdateTime which I update
> from
> application, however since I new to SQLServer (used to use Access) I want
> to
> insert/update these fields via trigger, the ModifyID should contain the
> user
> name logged on to the SQLServer and the time he modify or insert the row.
> Could this two insert/update containing in one trigger? Any help would be
> highly appreciated. TIA.
> Hendrick
>|||Great. Thanks for the prompt reply.
Hendrick
"Adam Machanic" <amachanic@.hotmail._removetoemail_.com> wrote in message
news:#VvKdYdzFHA.3124@.TK2MSFTNGP12.phx.gbl...
> CREATE TRIGGER YourTriggerName
> ON YourTable
> FOR INSERT, UPDATE
> AS
> BEGIN
> UPDATE YourTable
> SET
> UpdateTime = GETDATE(),
> UpdateID = USER_ID()
> WHERE YourTable.PK IN
> (
> SELECT PK
> FROM INSERTED
> )
> END
>
> ... Replace 'PK' with the primary key column(s) from your table.
>
> --
> Adam Machanic
> SQL Server MVP
> http://www.datamanipulation.net
> --
>
> "Hendrick" <hbouty@.not.gmail.com> wrote in message
> news:uZe0ITdzFHA.4032@.TK2MSFTNGP15.phx.gbl...
want[vbcol=seagreen]
row.[vbcol=seagreen]
be[vbcol=seagreen]
>|||Hendrick,
Also see 'Multirow Considerations' in the SQL Server Books Online.
HTH
Jerry
"Hendrick" <hbouty@.not.gmail.com> wrote in message
news:O4b8RddzFHA.3408@.TK2MSFTNGP09.phx.gbl...
> Great. Thanks for the prompt reply.
> Hendrick
> "Adam Machanic" <amachanic@.hotmail._removetoemail_.com> wrote in message
> news:#VvKdYdzFHA.3124@.TK2MSFTNGP12.phx.gbl...
> want
> row.
> be
>|||Hey Jerry,
Did a search on Multirow Considerations in my book online, didn't get
anything back.
(SQL SERVER 2000 sp4). Do you have a more specific indication of what we
should be aware of here? Always wanna learn more ;-)
Thanks,
Bob
"Jerry Spivey" <jspivey@.vestas-awt.com> wrote in message
news:unJ3T5dzFHA.2884@.TK2MSFTNGP09.phx.gbl...
> Hendrick,
> Also see 'Multirow Considerations' in the SQL Server Books Online.
> HTH
> Jerry
> "Hendrick" <hbouty@.not.gmail.com> wrote in message
> news:O4b8RddzFHA.3408@.TK2MSFTNGP09.phx.gbl...
>|||Bob,
Here is the 2005 link http://msdn2.microsoft.com/en-us/library/ms250511.
Are you using the latest SQL Server Books Online? Here is the link to
upgrade if not:
http://www.microsoft.com/sql/techin...2000/books.mspx
HTH
Jerry
"Bob" <bdufournosp@.sgiims.com> wrote in message
news:eWEpoEezFHA.3588@.tk2msftngp13.phx.gbl...
> Hey Jerry,
> Did a search on Multirow Considerations in my book online, didn't get
> anything back.
> (SQL SERVER 2000 sp4). Do you have a more specific indication of what we
> should be aware of here? Always wanna learn more ;-)
> Thanks,
> Bob
> "Jerry Spivey" <jspivey@.vestas-awt.com> wrote in message
> news:unJ3T5dzFHA.2884@.TK2MSFTNGP09.phx.gbl...
>
Newbie : How to make Trigger for inserting/updating fields?
Hi All,
I have fields ModifyID, ModifyTime, UpdateID, UpdateTime which I update from
application, however since I new to SQLServer (used to use Access) I want to
insert/update these fields via trigger, the ModifyID should contain the user
name logged on to the SQLServer and the time he modify or insert the row.
Could this two insert/update containing in one trigger? Any help would be
highly appreciated. TIA.
Hendrick
CREATE TRIGGER YourTriggerName
ON YourTable
FOR INSERT, UPDATE
AS
BEGIN
UPDATE YourTable
SET
UpdateTime = GETDATE(),
UpdateID = USER_ID()
WHERE YourTable.PK IN
(
SELECT PK
FROM INSERTED
)
END
... Replace 'PK' with the primary key column(s) from your table.
Adam Machanic
SQL Server MVP
http://www.datamanipulation.net
"Hendrick" <hbouty@.not.gmail.com> wrote in message
news:uZe0ITdzFHA.4032@.TK2MSFTNGP15.phx.gbl...
> Hi All,
> I have fields ModifyID, ModifyTime, UpdateID, UpdateTime which I update
> from
> application, however since I new to SQLServer (used to use Access) I want
> to
> insert/update these fields via trigger, the ModifyID should contain the
> user
> name logged on to the SQLServer and the time he modify or insert the row.
> Could this two insert/update containing in one trigger? Any help would be
> highly appreciated. TIA.
> Hendrick
>
|||Great. Thanks for the prompt reply.
Hendrick
"Adam Machanic" <amachanic@.hotmail._removetoemail_.com> wrote in message
news:#VvKdYdzFHA.3124@.TK2MSFTNGP12.phx.gbl...[vbcol=seagreen]
> CREATE TRIGGER YourTriggerName
> ON YourTable
> FOR INSERT, UPDATE
> AS
> BEGIN
> UPDATE YourTable
> SET
> UpdateTime = GETDATE(),
> UpdateID = USER_ID()
> WHERE YourTable.PK IN
> (
> SELECT PK
> FROM INSERTED
> )
> END
>
> ... Replace 'PK' with the primary key column(s) from your table.
>
> --
> Adam Machanic
> SQL Server MVP
> http://www.datamanipulation.net
> --
>
> "Hendrick" <hbouty@.not.gmail.com> wrote in message
> news:uZe0ITdzFHA.4032@.TK2MSFTNGP15.phx.gbl...
want[vbcol=seagreen]
row.[vbcol=seagreen]
be
>
|||Hendrick,
Also see 'Multirow Considerations' in the SQL Server Books Online.
HTH
Jerry
"Hendrick" <hbouty@.not.gmail.com> wrote in message
news:O4b8RddzFHA.3408@.TK2MSFTNGP09.phx.gbl...
> Great. Thanks for the prompt reply.
> Hendrick
> "Adam Machanic" <amachanic@.hotmail._removetoemail_.com> wrote in message
> news:#VvKdYdzFHA.3124@.TK2MSFTNGP12.phx.gbl...
> want
> row.
> be
>
|||Hey Jerry,
Did a search on Multirow Considerations in my book online, didn't get
anything back.
(SQL SERVER 2000 sp4). Do you have a more specific indication of what we
should be aware of here? Always wanna learn more ;-)
Thanks,
Bob
"Jerry Spivey" <jspivey@.vestas-awt.com> wrote in message
news:unJ3T5dzFHA.2884@.TK2MSFTNGP09.phx.gbl...
> Hendrick,
> Also see 'Multirow Considerations' in the SQL Server Books Online.
> HTH
> Jerry
> "Hendrick" <hbouty@.not.gmail.com> wrote in message
> news:O4b8RddzFHA.3408@.TK2MSFTNGP09.phx.gbl...
>
|||Bob,
Here is the 2005 link http://msdn2.microsoft.com/en-us/library/ms250511.
Are you using the latest SQL Server Books Online? Here is the link to
upgrade if not:
http://www.microsoft.com/sql/techinf...000/books.mspx
HTH
Jerry
"Bob" <bdufournosp@.sgiims.com> wrote in message
news:eWEpoEezFHA.3588@.tk2msftngp13.phx.gbl...
> Hey Jerry,
> Did a search on Multirow Considerations in my book online, didn't get
> anything back.
> (SQL SERVER 2000 sp4). Do you have a more specific indication of what we
> should be aware of here? Always wanna learn more ;-)
> Thanks,
> Bob
> "Jerry Spivey" <jspivey@.vestas-awt.com> wrote in message
> news:unJ3T5dzFHA.2884@.TK2MSFTNGP09.phx.gbl...
>
I have fields ModifyID, ModifyTime, UpdateID, UpdateTime which I update from
application, however since I new to SQLServer (used to use Access) I want to
insert/update these fields via trigger, the ModifyID should contain the user
name logged on to the SQLServer and the time he modify or insert the row.
Could this two insert/update containing in one trigger? Any help would be
highly appreciated. TIA.
Hendrick
CREATE TRIGGER YourTriggerName
ON YourTable
FOR INSERT, UPDATE
AS
BEGIN
UPDATE YourTable
SET
UpdateTime = GETDATE(),
UpdateID = USER_ID()
WHERE YourTable.PK IN
(
SELECT PK
FROM INSERTED
)
END
... Replace 'PK' with the primary key column(s) from your table.
Adam Machanic
SQL Server MVP
http://www.datamanipulation.net
"Hendrick" <hbouty@.not.gmail.com> wrote in message
news:uZe0ITdzFHA.4032@.TK2MSFTNGP15.phx.gbl...
> Hi All,
> I have fields ModifyID, ModifyTime, UpdateID, UpdateTime which I update
> from
> application, however since I new to SQLServer (used to use Access) I want
> to
> insert/update these fields via trigger, the ModifyID should contain the
> user
> name logged on to the SQLServer and the time he modify or insert the row.
> Could this two insert/update containing in one trigger? Any help would be
> highly appreciated. TIA.
> Hendrick
>
|||Great. Thanks for the prompt reply.
Hendrick
"Adam Machanic" <amachanic@.hotmail._removetoemail_.com> wrote in message
news:#VvKdYdzFHA.3124@.TK2MSFTNGP12.phx.gbl...[vbcol=seagreen]
> CREATE TRIGGER YourTriggerName
> ON YourTable
> FOR INSERT, UPDATE
> AS
> BEGIN
> UPDATE YourTable
> SET
> UpdateTime = GETDATE(),
> UpdateID = USER_ID()
> WHERE YourTable.PK IN
> (
> SELECT PK
> FROM INSERTED
> )
> END
>
> ... Replace 'PK' with the primary key column(s) from your table.
>
> --
> Adam Machanic
> SQL Server MVP
> http://www.datamanipulation.net
> --
>
> "Hendrick" <hbouty@.not.gmail.com> wrote in message
> news:uZe0ITdzFHA.4032@.TK2MSFTNGP15.phx.gbl...
want[vbcol=seagreen]
row.[vbcol=seagreen]
be
>
|||Hendrick,
Also see 'Multirow Considerations' in the SQL Server Books Online.
HTH
Jerry
"Hendrick" <hbouty@.not.gmail.com> wrote in message
news:O4b8RddzFHA.3408@.TK2MSFTNGP09.phx.gbl...
> Great. Thanks for the prompt reply.
> Hendrick
> "Adam Machanic" <amachanic@.hotmail._removetoemail_.com> wrote in message
> news:#VvKdYdzFHA.3124@.TK2MSFTNGP12.phx.gbl...
> want
> row.
> be
>
|||Hey Jerry,
Did a search on Multirow Considerations in my book online, didn't get
anything back.
(SQL SERVER 2000 sp4). Do you have a more specific indication of what we
should be aware of here? Always wanna learn more ;-)
Thanks,
Bob
"Jerry Spivey" <jspivey@.vestas-awt.com> wrote in message
news:unJ3T5dzFHA.2884@.TK2MSFTNGP09.phx.gbl...
> Hendrick,
> Also see 'Multirow Considerations' in the SQL Server Books Online.
> HTH
> Jerry
> "Hendrick" <hbouty@.not.gmail.com> wrote in message
> news:O4b8RddzFHA.3408@.TK2MSFTNGP09.phx.gbl...
>
|||Bob,
Here is the 2005 link http://msdn2.microsoft.com/en-us/library/ms250511.
Are you using the latest SQL Server Books Online? Here is the link to
upgrade if not:
http://www.microsoft.com/sql/techinf...000/books.mspx
HTH
Jerry
"Bob" <bdufournosp@.sgiims.com> wrote in message
news:eWEpoEezFHA.3588@.tk2msftngp13.phx.gbl...
> Hey Jerry,
> Did a search on Multirow Considerations in my book online, didn't get
> anything back.
> (SQL SERVER 2000 sp4). Do you have a more specific indication of what we
> should be aware of here? Always wanna learn more ;-)
> Thanks,
> Bob
> "Jerry Spivey" <jspivey@.vestas-awt.com> wrote in message
> news:unJ3T5dzFHA.2884@.TK2MSFTNGP09.phx.gbl...
>
Newbie (to Triggers) Trigger Help....
Where can I find good information about how to write triggers? I'm using SQL
Server 2000.
Now, the task at hand: How can I write a trigger that reacts on both insert
and update to keep some fields in two similar (but not the same) tables in
sync. (I need to both insert and update the 2nd table).
Here's some sample DBs (is there a better way to describe the database?):
CREATE TABLE [dbo][tblUserMain](
[userID] [int] IDENTITY (1, 1) NOT NULL ,
[CN] [nvarchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,
[userPassword] [nvarchar] (1024) COLLATE SQL_Latin1_General_CP1_CI_AS NOT
NULL ,
[dtLastActive] [datetime] NOT NULL ,
[GUID] [nvarchar] (64) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,
[firstName] [nvarchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,
[lastName] [nvarchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
[billCity] [nvarchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,
[billCountry] [nvarchar] (25) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL
,
[billName] [nvarchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,
[billPostal] [nvarchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL
,
[billProvince] [nvarchar] (25) COLLATE SQL_Latin1_General_CP1_CI_AS NOT
NULL ,
[billStreet1] [nvarchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL
,
[billStreet2] [nvarchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL
) ON [PRIMARY]
CREATE TABLE [dbo].[tblUserExt] (
[CN] [nvarchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,
[firstName] [nvarchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,
[lastName] [nvarchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,
[userEmail] [nvarchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,
[userRefBy] [nvarchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,
[userProfession] [nvarchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT
NULL ,
[userBulkMail] [nvarchar] (1) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL
,
[userSubspecialties] [nvarchar] (750) COLLATE SQL_Latin1_General_CP1_CI_AS
NOT NULL ,
[userTechnologies] [nvarchar] (750) COLLATE SQL_Latin1_General_CP1_CI_AS
NOT NULL ,
[dtRegDate] [datetime] NOT NULL ,
[userPopQuiz] [nchar] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,
[orgCity] [nvarchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,
[orgProvince] [nvarchar] (25) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL
,
[orgPostal] [nvarchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,
[orgCountry] [nvarchar] (25) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL
,
[orgType] [nvarchar] (25) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,
[userAdvertise] [nvarchar] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NOT
NULL ,
[userBulkMailHtml] [nchar] (1) COLLATE SQL_Latin1_General_CP1_CI_AS NOT
NULL ,
[userTitle] [nvarchar] (25) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,
[orgName] [nvarchar] (25) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,
[orgStreet1] [nvarchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL
,
[orgStreet2] [nvarchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL
,
[userHomeTelephone] [nvarchar] (25) COLLATE SQL_Latin1_General_CP1_CI_AS
NOT NULL ,
[userWorkTelephone] [nvarchar] (25) COLLATE SQL_Latin1_General_CP1_CI_AS
NOT NULL ,
[billCity] [nvarchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,
[billCountry] [nvarchar] (25) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL
,
[billName] [nvarchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,
[billPostal] [nvarchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL
,
[billProvince] [nvarchar] (25) COLLATE SQL_Latin1_General_CP1_CI_AS NOT
NULL ,
[billStreet1] [nvarchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL
,
[billStreet2] [nvarchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL
,
[userDegree] [nvarchar] (25) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL
,
[needsUpdate] [nchar] (1) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,
[SavedSearches] [nvarchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT
NULL ,
[userGroups] [nvarchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL
,
[userPersonalize] [nchar] (1) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL
,
[userRememberMe] [nchar] (1) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL
,
[middleName] [nvarchar] (25) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL
,
[needsUpdateMessage] [nvarchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS
NOT NULL ,
[pwdQuestion] [nvarchar] (250) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
[pwdAnswer] [nvarchar] (250) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
[homePage] [ntext] COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
[language] [nvarchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
[mailerEmailInvalid] [int] NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
I need a trigger so that when the lastName, firstName and bill* fields
change (or insert) in the tblUserExt table they get updated (or inserted)
into the tblUserMain table. These triggers would be temporary until the
tblUserExt table is made obsolete...
Pseudocode--
On Insert,
Update the name and bill* fields in the tblUserMain table (the row will
already exist)
On Update,
Update the name and bill* fields (if they changed) in the tblUserMain
table
TIA,
OwenCREATE TRIGGER Triger_name ON tblUserExt
FOR INSERT
AS
DECLARE @.name NVARCHAR(50)
DECLARE @.billname NVARCHAR(50)
SELECT @.name=name FROM INSERTED
SELECT @.billname=billname FROM INSERTED
INSERT INTO tblUserMain (name,billname) VALUES (@.name,@.billname)
-- or INSERT INTO tblUserMain (the required fields) SELECT
ins.the_same_required_ fileds FROM INSERTED ins
----
CREATE TRIGGER Triger_name ON tblUserExt
FOR UPDATE
AS
DECLARE @.name NVARCHAR(50)
DECLARE @.billname NVARCHAR(50)
DECLARE @.Oldname NVARCHAR(50) --before updated
DECLARE @.Oldbillname NVARCHAR(50)--before updated
SELECT @.name=name FROM INSERTED
SELECT @.billname=billname FROM INSERTED
SELECT @.Oldname=name FROM tblUserExt
SELECT @.Oldbillname=billname FROM tblUserExt
UPDATE tblUserMain
SET name = @.name,
billname = @.billname
WHERE name = @.name AND billname = @.Oldbillname
Note that @.name has to be changed to all the fields like
firstname,lastname,..., same thong for billname.
"Owen Mortensen" <ojm.NO_SPAM@.acm.org> a crit dans le message de news:
elI550wVFHA.3320@.TK2MSFTNGP12.phx.gbl...
> Where can I find good information about how to write triggers? I'm using
> SQL Server 2000.
> Now, the task at hand: How can I write a trigger that reacts on both
> insert and update to keep some fields in two similar (but not the same)
> tables in sync. (I need to both insert and update the 2nd table).
> Here's some sample DBs (is there a better way to describe the database?):
> CREATE TABLE [dbo][tblUserMain](
> [userID] [int] IDENTITY (1, 1) NOT NULL ,
> [CN] [nvarchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,
> [userPassword] [nvarchar] (1024) COLLATE SQL_Latin1_General_CP1_CI_AS NOT
> NULL ,
> [dtLastActive] [datetime] NOT NULL ,
> [GUID] [nvarchar] (64) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,
> [firstName] [nvarchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL
> ,
> [lastName] [nvarchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
> [billCity] [nvarchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,
> [billCountry] [nvarchar] (25) COLLATE SQL_Latin1_General_CP1_CI_AS NOT
> NULL ,
> [billName] [nvarchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,
> [billPostal] [nvarchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL
> ,
> [billProvince] [nvarchar] (25) COLLATE SQL_Latin1_General_CP1_CI_AS NOT
> NULL ,
> [billStreet1] [nvarchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT
> NULL ,
> [billStreet2] [nvarchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT
> NULL
> ) ON [PRIMARY]
> CREATE TABLE [dbo].[tblUserExt] (
> [CN] [nvarchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,
> [firstName] [nvarchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL
> ,
> [lastName] [nvarchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,
> [userEmail] [nvarchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL
> ,
> [userRefBy] [nvarchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL
> ,
> [userProfession] [nvarchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT
> NULL ,
> [userBulkMail] [nvarchar] (1) COLLATE SQL_Latin1_General_CP1_CI_AS NOT
> NULL ,
> [userSubspecialties] [nvarchar] (750) COLLATE SQL_Latin1_General_CP1_CI_AS
> NOT NULL ,
> [userTechnologies] [nvarchar] (750) COLLATE SQL_Latin1_General_CP1_CI_AS
> NOT NULL ,
> [dtRegDate] [datetime] NOT NULL ,
> [userPopQuiz] [nchar] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,
> [orgCity] [nvarchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,
> [orgProvince] [nvarchar] (25) COLLATE SQL_Latin1_General_CP1_CI_AS NOT
> NULL ,
> [orgPostal] [nvarchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL
> ,
> [orgCountry] [nvarchar] (25) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL
> ,
> [orgType] [nvarchar] (25) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,
> [userAdvertise] [nvarchar] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NOT
> NULL ,
> [userBulkMailHtml] [nchar] (1) COLLATE SQL_Latin1_General_CP1_CI_AS NOT
> NULL ,
> [userTitle] [nvarchar] (25) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL
> ,
> [orgName] [nvarchar] (25) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,
> [orgStreet1] [nvarchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL
> ,
> [orgStreet2] [nvarchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL
> ,
> [userHomeTelephone] [nvarchar] (25) COLLATE SQL_Latin1_General_CP1_CI_AS
> NOT NULL ,
> [userWorkTelephone] [nvarchar] (25) COLLATE SQL_Latin1_General_CP1_CI_AS
> NOT NULL ,
> [billCity] [nvarchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,
> [billCountry] [nvarchar] (25) COLLATE SQL_Latin1_General_CP1_CI_AS NOT
> NULL ,
> [billName] [nvarchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,
> [billPostal] [nvarchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL
> ,
> [billProvince] [nvarchar] (25) COLLATE SQL_Latin1_General_CP1_CI_AS NOT
> NULL ,
> [billStreet1] [nvarchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT
> NULL ,
> [billStreet2] [nvarchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT
> NULL ,
> [userDegree] [nvarchar] (25) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL
> ,
> [needsUpdate] [nchar] (1) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,
> [SavedSearches] [nvarchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT
> NULL ,
> [userGroups] [nvarchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL
> ,
> [userPersonalize] [nchar] (1) COLLATE SQL_Latin1_General_CP1_CI_AS NOT
> NULL ,
> [userRememberMe] [nchar] (1) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL
> ,
> [middleName] [nvarchar] (25) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL
> ,
> [needsUpdateMessage] [nvarchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS
> NOT NULL ,
> [pwdQuestion] [nvarchar] (250) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
> [pwdAnswer] [nvarchar] (250) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
> [homePage] [ntext] COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
> [language] [nvarchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
> [mailerEmailInvalid] [int] NULL
> ) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
> I need a trigger so that when the lastName, firstName and bill* fields
> change (or insert) in the tblUserExt table they get updated (or inserted)
> into the tblUserMain table. These triggers would be temporary until the
> tblUserExt table is made obsolete...
> Pseudocode--
> On Insert,
> Update the name and bill* fields in the tblUserMain table (the row will
> already exist)
> On Update,
> Update the name and bill* fields (if they changed) in the tblUserMain
> table
> TIA,
> Owen
>|||Regarding: "Here's some sample DBs (is there a better way to describe
the database?)" - What you have provided is fine, but any constraints
(primary key, unique and foreign keys) are also needed. If you
generated this thru Query Analyzer, you can set the options for DDL
generation.
Use the Tools-->Options menu item and then the scripts tab.
Here is part of an update trigger to syncronize the First and Last Name.
This assumes that, in both tables, the column named CN is unique and has
the same value. I have included the comparison logic for First and Last
Name allowing nulls.
CREATE TRIGGER tblUserExt_tua -- Trigger Update After
ON tblUserExt FOR UPDATE
AS
set nocount on
set xact_abort on
-- Check if any rows affected by the command
declare @.Rows integer
SELECT @.Rows = count(*) from inserted
IF @.rows = 0 return
UPDATE dbo.tblUserMain
SET firstName = inserted.firstName
, lastName = inserted.lastName
FROM inserted
WHERE dbo.tblUserMain.CN = inserted.CN
AND ( inserted.firstName <> dbo.tblUserMain.firstName
OR ( inserted.firstName IS NULL
and dbo.tblUserMain.firstName IS NOT NULL
)
OR ( inserted.firstName IS NOT NULL
and dbo.tblUserMain.firstName IS NULL
)
OR inserted.lastName <> dbo.tblUserMain.lastName
OR ( inserted.lastName IS NOT NULL
and dbo.tblUserMain.firstName IS NULL
)
OR ( inserted.lastName IS NULL
and dbo.tblUserMain.firstName IS NOT NULL
)
)
)
go
*** Sent via Developersdex http://www.examnotes.net ***|||On Thu, 12 May 2005 18:20:05 +0100, Berimi wrote:
>CREATE TRIGGER Triger_name ON tblUserExt
>FOR INSERT
>AS
>DECLARE @.name NVARCHAR(50)
>DECLARE @.billname NVARCHAR(50)
>SELECT @.name=name FROM INSERTED
>SELECT @.billname=billname FROM INSERTED
(snip)
Hi Berimi,
This trigger (and the trigger you wrote for UPDATE) will fail as soon as
an insert or update statement is executed that affects more than one
row. And it will fail even worse when a statement is executed that
affects no rows.
Always write triggers that can handle multi-row and zero-row operations!
Best, Hugo
--
(Remove _NO_ and _SPAM_ to get my e-mail address)|||On Thu, 12 May 2005 10:30:54 -0700, Carl Federl wrote:
(snip)
>CREATE TRIGGER tblUserExt_tua -- Trigger Update After
> ON tblUserExt FOR UPDATE
If I understand the OP's requirements correct, one trigger can handle
both inserts and updates:
ON tblUserExt FOR INSERT, UPDATE
>-- Check if any rows affected by the command
>declare @.Rows integer
>SELECT @.Rows = count(*) from inserted
>IF @.rows = 0 return
This will waste unnecessary time when 1000s of rows were affected. Use
EXISTS instead:
IF NOT EXISTS (SELECT * FROM inserted) RETURN
Or, better yet, use @.@.ROWCOUNT (at the start of a trigger, this holds
the number of rows affected by the stmt that fired the trigger):
IF @.@.ROWCOUNT = 0 RETURN
>UPDATE dbo.tblUserMain
>SET firstName = inserted.firstName
>, lastName = inserted.lastName
>FROM inserted
>WHERE dbo.tblUserMain.CN = inserted.CN
>AND ( inserted.firstName <> dbo.tblUserMain.firstName
> OR ( inserted.firstName IS NULL
> and dbo.tblUserMain.firstName IS NOT NULL
> )
> OR ( inserted.firstName IS NOT NULL
> and dbo.tblUserMain.firstName IS NULL
> )
> OR inserted.lastName <> dbo.tblUserMain.lastName
> OR ( inserted.lastName IS NOT NULL
> and dbo.tblUserMain.firstName IS NULL
> )
> OR ( inserted.lastName IS NULL
> and dbo.tblUserMain.firstName IS NOT NULL
> )
> )
> )
The test for changed data in nullable columns can be done in a shorter
form. It's less intuitive on first sight, but it saves you lots of lines
of code (important if this has to grow to accomodate 50-odd columns!),
and it's easy once you get used to it:
UPDATE u
SET firstName = i.firstName
, lastName = i.lastName
FROM dbo.tblUserMain AS u
INNER JOIN inserted AS i
ON i.CN = u.CN
WHERE ( NULLIF (i.firstName, u.firstName) IS NOT NULL
OR NULLIF (u.firstName, i.firstName) IS NOT NULL)
AND ( NULLIF (i.lastName, u.lastName) IS NOT NULL
OR NULLIF (u.lastName, i.lastName) IS NOT NULL)
Of course, the check for unchanged data could be left out completely.
Without it, finding the rows to operate on would be much quicker, at the
cost of possibly updating the values in some rows to the values they
already had. To prevent updating when no first or last names have been
changed, you can add (before the UPDATE statement):
IF UPDATE(FirstName) OR UPDATE(LastName)
Best, Hugo
--
(Remove _NO_ and _SPAM_ to get my e-mail address)|||You're right Hugo,
Thanks,
T.Berimi
"Hugo Kornelis" <hugo@.pe_NO_rFact.in_SPAM_fo> a crit dans le message de
news: l5l781lt68ctijp3ov37rjv7cd0m5l1ifu@.4ax.com...
> On Thu, 12 May 2005 18:20:05 +0100, Berimi wrote:
>
> (snip)
> Hi Berimi,
> This trigger (and the trigger you wrote for UPDATE) will fail as soon as
> an insert or update statement is executed that affects more than one
> row. And it will fail even worse when a statement is executed that
> affects no rows.
> Always write triggers that can handle multi-row and zero-row operations!
> Best, Hugo
> --
> (Remove _NO_ and _SPAM_ to get my e-mail address)
Server 2000.
Now, the task at hand: How can I write a trigger that reacts on both insert
and update to keep some fields in two similar (but not the same) tables in
sync. (I need to both insert and update the 2nd table).
Here's some sample DBs (is there a better way to describe the database?):
CREATE TABLE [dbo][tblUserMain](
[userID] [int] IDENTITY (1, 1) NOT NULL ,
[CN] [nvarchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,
[userPassword] [nvarchar] (1024) COLLATE SQL_Latin1_General_CP1_CI_AS NOT
NULL ,
[dtLastActive] [datetime] NOT NULL ,
[GUID] [nvarchar] (64) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,
[firstName] [nvarchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,
[lastName] [nvarchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
[billCity] [nvarchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,
[billCountry] [nvarchar] (25) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL
,
[billName] [nvarchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,
[billPostal] [nvarchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL
,
[billProvince] [nvarchar] (25) COLLATE SQL_Latin1_General_CP1_CI_AS NOT
NULL ,
[billStreet1] [nvarchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL
,
[billStreet2] [nvarchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL
) ON [PRIMARY]
CREATE TABLE [dbo].[tblUserExt] (
[CN] [nvarchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,
[firstName] [nvarchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,
[lastName] [nvarchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,
[userEmail] [nvarchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,
[userRefBy] [nvarchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,
[userProfession] [nvarchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT
NULL ,
[userBulkMail] [nvarchar] (1) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL
,
[userSubspecialties] [nvarchar] (750) COLLATE SQL_Latin1_General_CP1_CI_AS
NOT NULL ,
[userTechnologies] [nvarchar] (750) COLLATE SQL_Latin1_General_CP1_CI_AS
NOT NULL ,
[dtRegDate] [datetime] NOT NULL ,
[userPopQuiz] [nchar] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,
[orgCity] [nvarchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,
[orgProvince] [nvarchar] (25) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL
,
[orgPostal] [nvarchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,
[orgCountry] [nvarchar] (25) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL
,
[orgType] [nvarchar] (25) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,
[userAdvertise] [nvarchar] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NOT
NULL ,
[userBulkMailHtml] [nchar] (1) COLLATE SQL_Latin1_General_CP1_CI_AS NOT
NULL ,
[userTitle] [nvarchar] (25) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,
[orgName] [nvarchar] (25) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,
[orgStreet1] [nvarchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL
,
[orgStreet2] [nvarchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL
,
[userHomeTelephone] [nvarchar] (25) COLLATE SQL_Latin1_General_CP1_CI_AS
NOT NULL ,
[userWorkTelephone] [nvarchar] (25) COLLATE SQL_Latin1_General_CP1_CI_AS
NOT NULL ,
[billCity] [nvarchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,
[billCountry] [nvarchar] (25) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL
,
[billName] [nvarchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,
[billPostal] [nvarchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL
,
[billProvince] [nvarchar] (25) COLLATE SQL_Latin1_General_CP1_CI_AS NOT
NULL ,
[billStreet1] [nvarchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL
,
[billStreet2] [nvarchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL
,
[userDegree] [nvarchar] (25) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL
,
[needsUpdate] [nchar] (1) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,
[SavedSearches] [nvarchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT
NULL ,
[userGroups] [nvarchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL
,
[userPersonalize] [nchar] (1) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL
,
[userRememberMe] [nchar] (1) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL
,
[middleName] [nvarchar] (25) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL
,
[needsUpdateMessage] [nvarchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS
NOT NULL ,
[pwdQuestion] [nvarchar] (250) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
[pwdAnswer] [nvarchar] (250) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
[homePage] [ntext] COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
[language] [nvarchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
[mailerEmailInvalid] [int] NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
I need a trigger so that when the lastName, firstName and bill* fields
change (or insert) in the tblUserExt table they get updated (or inserted)
into the tblUserMain table. These triggers would be temporary until the
tblUserExt table is made obsolete...
Pseudocode--
On Insert,
Update the name and bill* fields in the tblUserMain table (the row will
already exist)
On Update,
Update the name and bill* fields (if they changed) in the tblUserMain
table
TIA,
OwenCREATE TRIGGER Triger_name ON tblUserExt
FOR INSERT
AS
DECLARE @.name NVARCHAR(50)
DECLARE @.billname NVARCHAR(50)
SELECT @.name=name FROM INSERTED
SELECT @.billname=billname FROM INSERTED
INSERT INTO tblUserMain (name,billname) VALUES (@.name,@.billname)
-- or INSERT INTO tblUserMain (the required fields) SELECT
ins.the_same_required_ fileds FROM INSERTED ins
----
CREATE TRIGGER Triger_name ON tblUserExt
FOR UPDATE
AS
DECLARE @.name NVARCHAR(50)
DECLARE @.billname NVARCHAR(50)
DECLARE @.Oldname NVARCHAR(50) --before updated
DECLARE @.Oldbillname NVARCHAR(50)--before updated
SELECT @.name=name FROM INSERTED
SELECT @.billname=billname FROM INSERTED
SELECT @.Oldname=name FROM tblUserExt
SELECT @.Oldbillname=billname FROM tblUserExt
UPDATE tblUserMain
SET name = @.name,
billname = @.billname
WHERE name = @.name AND billname = @.Oldbillname
Note that @.name has to be changed to all the fields like
firstname,lastname,..., same thong for billname.
"Owen Mortensen" <ojm.NO_SPAM@.acm.org> a crit dans le message de news:
elI550wVFHA.3320@.TK2MSFTNGP12.phx.gbl...
> Where can I find good information about how to write triggers? I'm using
> SQL Server 2000.
> Now, the task at hand: How can I write a trigger that reacts on both
> insert and update to keep some fields in two similar (but not the same)
> tables in sync. (I need to both insert and update the 2nd table).
> Here's some sample DBs (is there a better way to describe the database?):
> CREATE TABLE [dbo][tblUserMain](
> [userID] [int] IDENTITY (1, 1) NOT NULL ,
> [CN] [nvarchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,
> [userPassword] [nvarchar] (1024) COLLATE SQL_Latin1_General_CP1_CI_AS NOT
> NULL ,
> [dtLastActive] [datetime] NOT NULL ,
> [GUID] [nvarchar] (64) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,
> [firstName] [nvarchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL
> ,
> [lastName] [nvarchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
> [billCity] [nvarchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,
> [billCountry] [nvarchar] (25) COLLATE SQL_Latin1_General_CP1_CI_AS NOT
> NULL ,
> [billName] [nvarchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,
> [billPostal] [nvarchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL
> ,
> [billProvince] [nvarchar] (25) COLLATE SQL_Latin1_General_CP1_CI_AS NOT
> NULL ,
> [billStreet1] [nvarchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT
> NULL ,
> [billStreet2] [nvarchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT
> NULL
> ) ON [PRIMARY]
> CREATE TABLE [dbo].[tblUserExt] (
> [CN] [nvarchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,
> [firstName] [nvarchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL
> ,
> [lastName] [nvarchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,
> [userEmail] [nvarchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL
> ,
> [userRefBy] [nvarchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL
> ,
> [userProfession] [nvarchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT
> NULL ,
> [userBulkMail] [nvarchar] (1) COLLATE SQL_Latin1_General_CP1_CI_AS NOT
> NULL ,
> [userSubspecialties] [nvarchar] (750) COLLATE SQL_Latin1_General_CP1_CI_AS
> NOT NULL ,
> [userTechnologies] [nvarchar] (750) COLLATE SQL_Latin1_General_CP1_CI_AS
> NOT NULL ,
> [dtRegDate] [datetime] NOT NULL ,
> [userPopQuiz] [nchar] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,
> [orgCity] [nvarchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,
> [orgProvince] [nvarchar] (25) COLLATE SQL_Latin1_General_CP1_CI_AS NOT
> NULL ,
> [orgPostal] [nvarchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL
> ,
> [orgCountry] [nvarchar] (25) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL
> ,
> [orgType] [nvarchar] (25) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,
> [userAdvertise] [nvarchar] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NOT
> NULL ,
> [userBulkMailHtml] [nchar] (1) COLLATE SQL_Latin1_General_CP1_CI_AS NOT
> NULL ,
> [userTitle] [nvarchar] (25) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL
> ,
> [orgName] [nvarchar] (25) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,
> [orgStreet1] [nvarchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL
> ,
> [orgStreet2] [nvarchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL
> ,
> [userHomeTelephone] [nvarchar] (25) COLLATE SQL_Latin1_General_CP1_CI_AS
> NOT NULL ,
> [userWorkTelephone] [nvarchar] (25) COLLATE SQL_Latin1_General_CP1_CI_AS
> NOT NULL ,
> [billCity] [nvarchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,
> [billCountry] [nvarchar] (25) COLLATE SQL_Latin1_General_CP1_CI_AS NOT
> NULL ,
> [billName] [nvarchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,
> [billPostal] [nvarchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL
> ,
> [billProvince] [nvarchar] (25) COLLATE SQL_Latin1_General_CP1_CI_AS NOT
> NULL ,
> [billStreet1] [nvarchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT
> NULL ,
> [billStreet2] [nvarchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT
> NULL ,
> [userDegree] [nvarchar] (25) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL
> ,
> [needsUpdate] [nchar] (1) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,
> [SavedSearches] [nvarchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT
> NULL ,
> [userGroups] [nvarchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL
> ,
> [userPersonalize] [nchar] (1) COLLATE SQL_Latin1_General_CP1_CI_AS NOT
> NULL ,
> [userRememberMe] [nchar] (1) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL
> ,
> [middleName] [nvarchar] (25) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL
> ,
> [needsUpdateMessage] [nvarchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS
> NOT NULL ,
> [pwdQuestion] [nvarchar] (250) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
> [pwdAnswer] [nvarchar] (250) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
> [homePage] [ntext] COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
> [language] [nvarchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
> [mailerEmailInvalid] [int] NULL
> ) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
> I need a trigger so that when the lastName, firstName and bill* fields
> change (or insert) in the tblUserExt table they get updated (or inserted)
> into the tblUserMain table. These triggers would be temporary until the
> tblUserExt table is made obsolete...
> Pseudocode--
> On Insert,
> Update the name and bill* fields in the tblUserMain table (the row will
> already exist)
> On Update,
> Update the name and bill* fields (if they changed) in the tblUserMain
> table
> TIA,
> Owen
>|||Regarding: "Here's some sample DBs (is there a better way to describe
the database?)" - What you have provided is fine, but any constraints
(primary key, unique and foreign keys) are also needed. If you
generated this thru Query Analyzer, you can set the options for DDL
generation.
Use the Tools-->Options menu item and then the scripts tab.
Here is part of an update trigger to syncronize the First and Last Name.
This assumes that, in both tables, the column named CN is unique and has
the same value. I have included the comparison logic for First and Last
Name allowing nulls.
CREATE TRIGGER tblUserExt_tua -- Trigger Update After
ON tblUserExt FOR UPDATE
AS
set nocount on
set xact_abort on
-- Check if any rows affected by the command
declare @.Rows integer
SELECT @.Rows = count(*) from inserted
IF @.rows = 0 return
UPDATE dbo.tblUserMain
SET firstName = inserted.firstName
, lastName = inserted.lastName
FROM inserted
WHERE dbo.tblUserMain.CN = inserted.CN
AND ( inserted.firstName <> dbo.tblUserMain.firstName
OR ( inserted.firstName IS NULL
and dbo.tblUserMain.firstName IS NOT NULL
)
OR ( inserted.firstName IS NOT NULL
and dbo.tblUserMain.firstName IS NULL
)
OR inserted.lastName <> dbo.tblUserMain.lastName
OR ( inserted.lastName IS NOT NULL
and dbo.tblUserMain.firstName IS NULL
)
OR ( inserted.lastName IS NULL
and dbo.tblUserMain.firstName IS NOT NULL
)
)
)
go
*** Sent via Developersdex http://www.examnotes.net ***|||On Thu, 12 May 2005 18:20:05 +0100, Berimi wrote:
>CREATE TRIGGER Triger_name ON tblUserExt
>FOR INSERT
>AS
>DECLARE @.name NVARCHAR(50)
>DECLARE @.billname NVARCHAR(50)
>SELECT @.name=name FROM INSERTED
>SELECT @.billname=billname FROM INSERTED
(snip)
Hi Berimi,
This trigger (and the trigger you wrote for UPDATE) will fail as soon as
an insert or update statement is executed that affects more than one
row. And it will fail even worse when a statement is executed that
affects no rows.
Always write triggers that can handle multi-row and zero-row operations!
Best, Hugo
--
(Remove _NO_ and _SPAM_ to get my e-mail address)|||On Thu, 12 May 2005 10:30:54 -0700, Carl Federl wrote:
(snip)
>CREATE TRIGGER tblUserExt_tua -- Trigger Update After
> ON tblUserExt FOR UPDATE
If I understand the OP's requirements correct, one trigger can handle
both inserts and updates:
ON tblUserExt FOR INSERT, UPDATE
>-- Check if any rows affected by the command
>declare @.Rows integer
>SELECT @.Rows = count(*) from inserted
>IF @.rows = 0 return
This will waste unnecessary time when 1000s of rows were affected. Use
EXISTS instead:
IF NOT EXISTS (SELECT * FROM inserted) RETURN
Or, better yet, use @.@.ROWCOUNT (at the start of a trigger, this holds
the number of rows affected by the stmt that fired the trigger):
IF @.@.ROWCOUNT = 0 RETURN
>UPDATE dbo.tblUserMain
>SET firstName = inserted.firstName
>, lastName = inserted.lastName
>FROM inserted
>WHERE dbo.tblUserMain.CN = inserted.CN
>AND ( inserted.firstName <> dbo.tblUserMain.firstName
> OR ( inserted.firstName IS NULL
> and dbo.tblUserMain.firstName IS NOT NULL
> )
> OR ( inserted.firstName IS NOT NULL
> and dbo.tblUserMain.firstName IS NULL
> )
> OR inserted.lastName <> dbo.tblUserMain.lastName
> OR ( inserted.lastName IS NOT NULL
> and dbo.tblUserMain.firstName IS NULL
> )
> OR ( inserted.lastName IS NULL
> and dbo.tblUserMain.firstName IS NOT NULL
> )
> )
> )
The test for changed data in nullable columns can be done in a shorter
form. It's less intuitive on first sight, but it saves you lots of lines
of code (important if this has to grow to accomodate 50-odd columns!),
and it's easy once you get used to it:
UPDATE u
SET firstName = i.firstName
, lastName = i.lastName
FROM dbo.tblUserMain AS u
INNER JOIN inserted AS i
ON i.CN = u.CN
WHERE ( NULLIF (i.firstName, u.firstName) IS NOT NULL
OR NULLIF (u.firstName, i.firstName) IS NOT NULL)
AND ( NULLIF (i.lastName, u.lastName) IS NOT NULL
OR NULLIF (u.lastName, i.lastName) IS NOT NULL)
Of course, the check for unchanged data could be left out completely.
Without it, finding the rows to operate on would be much quicker, at the
cost of possibly updating the values in some rows to the values they
already had. To prevent updating when no first or last names have been
changed, you can add (before the UPDATE statement):
IF UPDATE(FirstName) OR UPDATE(LastName)
Best, Hugo
--
(Remove _NO_ and _SPAM_ to get my e-mail address)|||You're right Hugo,
Thanks,
T.Berimi
"Hugo Kornelis" <hugo@.pe_NO_rFact.in_SPAM_fo> a crit dans le message de
news: l5l781lt68ctijp3ov37rjv7cd0m5l1ifu@.4ax.com...
> On Thu, 12 May 2005 18:20:05 +0100, Berimi wrote:
>
> (snip)
> Hi Berimi,
> This trigger (and the trigger you wrote for UPDATE) will fail as soon as
> an insert or update statement is executed that affects more than one
> row. And it will fail even worse when a statement is executed that
> affects no rows.
> Always write triggers that can handle multi-row and zero-row operations!
> Best, Hugo
> --
> (Remove _NO_ and _SPAM_ to get my e-mail address)
Monday, February 20, 2012
Newbie
Friends,
I am a newbie in sql programming, I don't know much about the programming.
I 've tried to make a trigger but it failed.
Where can I learn about it and rather free for payments. ( Sorry about that
statement, cause it rather expensive for my revenue)
--
Message posted via http://www.sqlmonster.comTry to learn it in BOL
Madhivanan|||In case you are not aware... BOL = Books Online, which is the help that
comes with the SQL Server client utilities. You can also get a lot of
information from Microsoft's website (www.microsoft.com). If you have
specific questions, then you can of course post them here.
-Tom.
NewBee Trigger Question
I want to create a basic insert trigger. In T1 I add a row, which creates
a
new ID. The trigger fires after the insert, how do I get the new ID to add
to the child table?
I know this is as simple as it gets but I've read about 10 posts and dont'
see it?
Thanks in advance.
Greg P.CREATE TRIGGER YourTriggerName
ON T1
FOR INSERT
AS
DECLARE @.newid int
IF @.@.ROWCOUNT=1
BEGIN
SET @.newid=(Select col1 FROM inserted)
--Do what you want do to with the @.newid here
END
Nathan H. Omukwenyi
"Greg P" <gsp@.newsgroups.nospam> wrote in message
news:872807BA-17FA-47A7-AAE1-AAF397488904@.microsoft.com...
>I want to create a basic insert trigger. In T1 I add a row, which creates
>a
> new ID. The trigger fires after the insert, how do I get the new ID to
> add
> to the child table?
> I know this is as simple as it gets but I've read about 10 posts and dont'
> see it?
> Thanks in advance.
> Greg P.|||try this...
create trigger trig1 on T1 after insert
as
begin
insert into [child table] ([new id])
select [new id] from inserted
end
"Greg P" wrote:
> I want to create a basic insert trigger. In T1 I add a row, which create
s a
> new ID. The trigger fires after the insert, how do I get the new ID to ad
d
> to the child table?
> I know this is as simple as it gets but I've read about 10 posts and dont'
> see it?
> Thanks in advance.
> Greg P.|||I read up on how to use the inserted table and this seems to answer the
question I posted, yet i have a bit of a different use than what was posted.
I need to look up values in two other tables before I can do my insert. I a
m
doing this with cursors. From what I am understanding I can't Declare
anything in a trigger, so to use the cursors I am calling a stored procedure
.
Inside this stored procedure is where I need to access the data in the
inserted table. Should I create a temp table and somehow copy the info from
the Inserted table into there?
FYI: I want to insert initail values for a 3 unique Id's into a 4th table.
So the inserted table contain the first ID's and I open cursors to store the
other 2 sets of ids. Then I am nesting the three cursors to insert a row fo
r
each of the three ID combinations.
IDCol1 IDCol2 IDCol 3 Tbl4Col
1 1 1 0
1 1 2 0
1 2 1 0
2 1 1 0
2 1 2 0
2 2 1 0
ect...
I hope that all makes sense. From what I know I can't do this in a trigger,
maye I can?
Thanks,
Greg
"Nathan H. Omukwenyi" wrote:
> CREATE TRIGGER YourTriggerName
> ON T1
> FOR INSERT
> AS
> DECLARE @.newid int
> IF @.@.ROWCOUNT=1
> BEGIN
> SET @.newid=(Select col1 FROM inserted)
> --Do what you want do to with the @.newid here
> END
>
> Nathan H. Omukwenyi
> "Greg P" <gsp@.newsgroups.nospam> wrote in message
> news:872807BA-17FA-47A7-AAE1-AAF397488904@.microsoft.com...
>
>|||Omni,
Any ideas on my new post?
Thanks,
Greg p
"Omnibuzz" wrote:
> try this...
> create trigger trig1 on T1 after insert
> as
> begin
> insert into [child table] ([new id])
> select [new id] from inserted
> end
> --
>
>
> "Greg P" wrote:
>|||>> want to create a basic insert trigger. In T1 I add a row, which creates a new ID
[sic]. The trigger fires after the insert, how do I get the new ID to add to the chil
d [sic] table? <<
Stop using SQL and go back to a network database. You have described
how they work as they build pointer chains as the data is inserted. I
am not kidding -- read a DB history book. You even used the term
"child" instead of "referenced" table!! Pure network/pointer chain
database concepts and terms, not anything like RDBMS.
Perhaps you should have read one book on RDBMS instead?
You do not create a relational key. It already exists in the real
world and you discover it.
Triggers are a kludge for putting procedural code into a declarative
language.
You need to start over; you do not know what you are doing. People
here will give you kludges to get rid of you quickly because we cannot
give you a 1-2 year course in RDBMS. Telling someone to "smash rats
with a rock when they get near your baby" is easier than "improve the
sewer system by learning civil engineering so rats are not a problem"
Look up this article: http://www.apa.org/journals/psp/psp7761121.html
Journal of Personality and Social Psychology
Unskilled and Unaware of It: How Difficulties in Recognizing One's Own
Incompetence Lead to Inflated Self-Assessments
Remember it takes SIX years to become a Union Journeyman Carpenter in
New York State. How many years to be an SQL programmer? A few w
s
in a ceritificate training class!|||On Tue, 9 May 2006 13:10:02 -0700, Greg P wrote:
>I read up on how to use the inserted table and this seems to answer the
>question I posted, yet i have a bit of a different use than what was posted
.
>I need to look up values in two other tables before I can do my insert. I
am
>doing this with cursors. From what I am understanding I can't Declare
>anything in a trigger, so to use the cursors I am calling a stored procedure.[/colo
r]
Hi Greg,
First misunderstanding: you CAN declare anything in a trigger. Whoever
told you otherwise obviously has little experience and even less
knowledge of SQL Server.
Second misunderstanding: Never ever use a cursor (*). And especially not
inside a trigger. Unless you want to ruin your performance and your
scalability, of course.
(*) Okay, there are SOME situations where a cursor is the best choice,
but they are very rare - only experienced DB programmers should be
allowed to use cursors, because it takes a lot of experience to
recognize a situation that might benefit from a cursor.
>Inside this stored procedure is where I need to access the data in the
>inserted table. Should I create a temp table and somehow copy the info fro
m
>the Inserted table into there?
If you MUST use the values from the inserted table in a stored
procedure, then yes, you must copy the data from inserted to some other
(preferably temporary) table.
But I don't think that this is the correct solution in your case.
>FYI: I want to insert initail values for a 3 unique Id's into a 4th table.
>So the inserted table contain the first ID's and I open cursors to store th
e
>other 2 sets of ids. Then I am nesting the three cursors to insert a row f
or
>each of the three ID combinations.
>IDCol1 IDCol2 IDCol 3 Tbl4Col
> 1 1 1 0
> 1 1 2 0
> 1 2 1 0
> 2 1 1 0
> 2 1 2 0
> 2 2 1 0
>ect...
>I hope that all makes sense.
To be blunt - not at all.
Please post the structure of all relevant tables, as CREATE TABLE
statements. Don't forget to include all constraints, properties and
indexes. Then, post some illustrative sample rows of data (as INSERT
statements), one or two sample INSERT statements that should fire the
trigger and the end results you need to have in your table after the
trigger has finished execution. With that information, we can probably
help you write this trigger without cursors or temp tables.
Hugo Kornelis, SQL Server MVP|||Hugo,
Thanks for the response. What I'm looking do is actually quite easily
explain. I'll use 4 tables and three relationsip, Widgets (WidegetsID PK),
Colors(ColorsIDPK), Sizes(SizesID PK) and WidgetsUsed (WidgetsUsedID,
WidgetsID FK, ColorsID Fk, )
I do an insert of multiple widgets creating multiple rows which are stored
in the "Insert" Table of the trigger. When a new Widget is inserted I need
to initialize the WidgetsUsed table. This means inserting a new record for
each size and color possibility and setting . (This table will need a row fo
r
each color and size that widget can come in)
If 2 Widgets were added A and B, and the colors are stored in the colors
table, and the sizes are stored in the sizes table. For this example lets
say there are three color in the color table and two sizes in the color
table. So for each Widget inserted into the widget table I want to add 6
records into the Widgets used table. Finally I'll call the field in the
table I'm updating MyDataField.
I know the idea of using curosr is bad now and they they are very
inefficient, but what I was thinking was I would use the cursors like old
adodb recordsets and loop through each one like the procedure below. I thin
k
this is a pretty thourough description of what I'm doing. Thanks for your
effort.
CREATE TABLE [dbo].[tblWidgetsUsed](
[WidgetUsedID] [uniqueidentifier] NULL,
[WidgetID] [uniqueidentifier] NULL,
[ColorID] [uniqueidentifier] NULL,
[SizeID] [uniqueidentifier] NULL,
[WidgetsOrdered] [numeric](18, 0) NULL
) ON [PRIMARY]
CREATE PROCEDURE dbo.spTrigUtilInsert
-- Add the parameters for the stored procedure here
@.WidgetID as int = 0,
@.ColorId as int = 0,
@.SizeID as int = 0
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
Declare curWidget Cursor for
SELECT WidgetID FROM tblTemp --created from Insert in the trigger
open curWidget
fetch next from curWidget into @.WidgetID
--for each newly insertered record
while (@.@.Fetch_Status <> -1)
Declare curColor Cursor for SELECT ColorID FROM dbo.tblColor
open curColor
Fetch next from curColor into @.ColorID
-- For each Color
while (@.@.Fetch_Status <> -1)
-- Each Size
Declare curSize Cursor for SELECT DISTINCT SizeID FROM
dbo.tblSize
open curSize
fetch next from curSize into @.SizeID
While (@.@.Fetch_Status<>-1)
insert into tblWidgetsOrdered("WidgetID", "ColorID", "SizeID",
"NumOrdered")
Values (@.WidgetId, @.ColorID, @.SizeID, 0)
END
GO
Obviously these are not my real tables, because of security issues with my
project I can't use real tables but I think this show you what I'm looking t
o
do. I am using VS2005 Windows form (which is why I discuussed child and
parent tables, because I need to handle the insert order myself... I will
have a reply for the extreemly rude gent that is all high and mighty...)
Let me know what you think the way to do this is. I'm upgrading an access
based app to SQL Server 2005 and would like to take advantage of triggers to
initalize these rows. In the old applicaiton recordsets did the work.
Thanks again Hugo.
Greg P.
"Hugo Kornelis" wrote:
> On Tue, 9 May 2006 13:10:02 -0700, Greg P wrote:
>
> Hi Greg,
> First misunderstanding: you CAN declare anything in a trigger. Whoever
> told you otherwise obviously has little experience and even less
> knowledge of SQL Server.
> Second misunderstanding: Never ever use a cursor (*). And especially not
> inside a trigger. Unless you want to ruin your performance and your
> scalability, of course.
> (*) Okay, there are SOME situations where a cursor is the best choice,
> but they are very rare - only experienced DB programmers should be
> allowed to use cursors, because it takes a lot of experience to
> recognize a situation that might benefit from a cursor.
>
> If you MUST use the values from the inserted table in a stored
> procedure, then yes, you must copy the data from inserted to some other
> (preferably temporary) table.
> But I don't think that this is the correct solution in your case.
>
> To be blunt - not at all.
> Please post the structure of all relevant tables, as CREATE TABLE
> statements. Don't forget to include all constraints, properties and
> indexes. Then, post some illustrative sample rows of data (as INSERT
> statements), one or two sample INSERT statements that should fire the
> trigger and the end results you need to have in your table after the
> trigger has finished execution. With that information, we can probably
> help you write this trigger without cursors or temp tables.
> --
> Hugo Kornelis, SQL Server MVP
>|||For anyone else reading this please do not think I would ever speak this way
if it were not for the post this gentlemen made first.
Hey Genius,
Mr F&*%ing high and mighty... did you see the title of the post. I admitted
to being unfamiliar to using Triggers and Cursors and was looking for some
advice from this newsgroup. Your slam of a person who claims to be
unknowledgeable in topic shows absolute insecurity you informed prick. Yes
once again I will say you are more informed more than me about this, that’
s
why I’m asking the questions moron!!! You could explain nicely what issue
s
have yet I would have to charge you $150 an hour to be your psychologist
because I’m sure no one else want to talk to you and it still isn’t enou
gh
money to listen to your useless babble.
FYI, I have a degree in computer science and do understand RDBMS very
clearly. I have designed and implemented many solutions in many different
technologies. Now I’m learning to work with a new one, SQL Server 2005.
I know that when you update tables in VS2005 you need to handle the
add/mod/deletes yourself through typed datasets. These method must be calle
d
by hand and the terminology used for this process includes Parent, Child, an
d
Grandchild tables. Here is one link to such a reference in the updating
multiple tables section:
http://www.15seconds.com/issue/051123.htm
I also have a WROX’s Visual Basic 2005 Database Programming book in front
of
me, which is the “most advanced” book in this series which even has a di
agram
on page 173 discussing the use of Parent, Child and Grandchild insert, updat
e
and deletes.
So now I have to question what do you really know? It seems to me not much.
You can talk very loud and very rudely… yet not very intelligently. Pleas
e
do not lower the average IQ of my posts again with your “knowledge”.
Regards,
Greg P.
"--CELKO--" wrote:
> Stop using SQL and go back to a network database. You have described
> how they work as they build pointer chains as the data is inserted. I
> am not kidding -- read a DB history book. You even used the term
> "child" instead of "referenced" table!! Pure network/pointer chain
> database concepts and terms, not anything like RDBMS.
>
> Perhaps you should have read one book on RDBMS instead?
> You do not create a relational key. It already exists in the real
> world and you discover it.
> Triggers are a kludge for putting procedural code into a declarative
> language.
> You need to start over; you do not know what you are doing. People
> here will give you kludges to get rid of you quickly because we cannot
> give you a 1-2 year course in RDBMS. Telling someone to "smash rats
> with a rock when they get near your baby" is easier than "improve the
> sewer system by learning civil engineering so rats are not a problem"
> Look up this article: http://www.apa.org/journals/psp/psp7761121.html
> Journal of Personality and Social Psychology
> Unskilled and Unaware of It: How Difficulties in Recognizing One's Own
> Incompetence Lead to Inflated Self-Assessments
> Remember it takes SIX years to become a Union Journeyman Carpenter in
> New York State. How many years to be an SQL programmer? A few w
s
> in a ceritificate training class!
>|||Greg,
I dunno if this is what you want. And sorry for the delayed reply.. And
try to decipher this because I just got up from bed :)
try this...
create trigger trig1 on Widgets after insert
as
begin
insert into WidgetsUsed(WidgetID, ColorID, SizeID, NumOrdered)
select
a.WidegetsID,
b.colorsID,
c.sizesID,
0
from inserted a,
colors B,
sizes c
end
Let me know if this was what you wanted.
a
new ID. The trigger fires after the insert, how do I get the new ID to add
to the child table?
I know this is as simple as it gets but I've read about 10 posts and dont'
see it?
Thanks in advance.
Greg P.CREATE TRIGGER YourTriggerName
ON T1
FOR INSERT
AS
DECLARE @.newid int
IF @.@.ROWCOUNT=1
BEGIN
SET @.newid=(Select col1 FROM inserted)
--Do what you want do to with the @.newid here
END
Nathan H. Omukwenyi
"Greg P" <gsp@.newsgroups.nospam> wrote in message
news:872807BA-17FA-47A7-AAE1-AAF397488904@.microsoft.com...
>I want to create a basic insert trigger. In T1 I add a row, which creates
>a
> new ID. The trigger fires after the insert, how do I get the new ID to
> add
> to the child table?
> I know this is as simple as it gets but I've read about 10 posts and dont'
> see it?
> Thanks in advance.
> Greg P.|||try this...
create trigger trig1 on T1 after insert
as
begin
insert into [child table] ([new id])
select [new id] from inserted
end
"Greg P" wrote:
> I want to create a basic insert trigger. In T1 I add a row, which create
s a
> new ID. The trigger fires after the insert, how do I get the new ID to ad
d
> to the child table?
> I know this is as simple as it gets but I've read about 10 posts and dont'
> see it?
> Thanks in advance.
> Greg P.|||I read up on how to use the inserted table and this seems to answer the
question I posted, yet i have a bit of a different use than what was posted.
I need to look up values in two other tables before I can do my insert. I a
m
doing this with cursors. From what I am understanding I can't Declare
anything in a trigger, so to use the cursors I am calling a stored procedure
.
Inside this stored procedure is where I need to access the data in the
inserted table. Should I create a temp table and somehow copy the info from
the Inserted table into there?
FYI: I want to insert initail values for a 3 unique Id's into a 4th table.
So the inserted table contain the first ID's and I open cursors to store the
other 2 sets of ids. Then I am nesting the three cursors to insert a row fo
r
each of the three ID combinations.
IDCol1 IDCol2 IDCol 3 Tbl4Col
1 1 1 0
1 1 2 0
1 2 1 0
2 1 1 0
2 1 2 0
2 2 1 0
ect...
I hope that all makes sense. From what I know I can't do this in a trigger,
maye I can?
Thanks,
Greg
"Nathan H. Omukwenyi" wrote:
> CREATE TRIGGER YourTriggerName
> ON T1
> FOR INSERT
> AS
> DECLARE @.newid int
> IF @.@.ROWCOUNT=1
> BEGIN
> SET @.newid=(Select col1 FROM inserted)
> --Do what you want do to with the @.newid here
> END
>
> Nathan H. Omukwenyi
> "Greg P" <gsp@.newsgroups.nospam> wrote in message
> news:872807BA-17FA-47A7-AAE1-AAF397488904@.microsoft.com...
>
>|||Omni,
Any ideas on my new post?
Thanks,
Greg p
"Omnibuzz" wrote:
> try this...
> create trigger trig1 on T1 after insert
> as
> begin
> insert into [child table] ([new id])
> select [new id] from inserted
> end
> --
>
>
> "Greg P" wrote:
>|||>> want to create a basic insert trigger. In T1 I add a row, which creates a new ID
[sic]. The trigger fires after the insert, how do I get the new ID to add to the chil
d [sic] table? <<
Stop using SQL and go back to a network database. You have described
how they work as they build pointer chains as the data is inserted. I
am not kidding -- read a DB history book. You even used the term
"child" instead of "referenced" table!! Pure network/pointer chain
database concepts and terms, not anything like RDBMS.
Perhaps you should have read one book on RDBMS instead?
You do not create a relational key. It already exists in the real
world and you discover it.
Triggers are a kludge for putting procedural code into a declarative
language.
You need to start over; you do not know what you are doing. People
here will give you kludges to get rid of you quickly because we cannot
give you a 1-2 year course in RDBMS. Telling someone to "smash rats
with a rock when they get near your baby" is easier than "improve the
sewer system by learning civil engineering so rats are not a problem"
Look up this article: http://www.apa.org/journals/psp/psp7761121.html
Journal of Personality and Social Psychology
Unskilled and Unaware of It: How Difficulties in Recognizing One's Own
Incompetence Lead to Inflated Self-Assessments
Remember it takes SIX years to become a Union Journeyman Carpenter in
New York State. How many years to be an SQL programmer? A few w
in a ceritificate training class!|||On Tue, 9 May 2006 13:10:02 -0700, Greg P wrote:
>I read up on how to use the inserted table and this seems to answer the
>question I posted, yet i have a bit of a different use than what was posted
.
>I need to look up values in two other tables before I can do my insert. I
am
>doing this with cursors. From what I am understanding I can't Declare
>anything in a trigger, so to use the cursors I am calling a stored procedure.[/colo
r]
Hi Greg,
First misunderstanding: you CAN declare anything in a trigger. Whoever
told you otherwise obviously has little experience and even less
knowledge of SQL Server.
Second misunderstanding: Never ever use a cursor (*). And especially not
inside a trigger. Unless you want to ruin your performance and your
scalability, of course.
(*) Okay, there are SOME situations where a cursor is the best choice,
but they are very rare - only experienced DB programmers should be
allowed to use cursors, because it takes a lot of experience to
recognize a situation that might benefit from a cursor.
>Inside this stored procedure is where I need to access the data in the
>inserted table. Should I create a temp table and somehow copy the info fro
m
>the Inserted table into there?
If you MUST use the values from the inserted table in a stored
procedure, then yes, you must copy the data from inserted to some other
(preferably temporary) table.
But I don't think that this is the correct solution in your case.
>FYI: I want to insert initail values for a 3 unique Id's into a 4th table.
>So the inserted table contain the first ID's and I open cursors to store th
e
>other 2 sets of ids. Then I am nesting the three cursors to insert a row f
or
>each of the three ID combinations.
>IDCol1 IDCol2 IDCol 3 Tbl4Col
> 1 1 1 0
> 1 1 2 0
> 1 2 1 0
> 2 1 1 0
> 2 1 2 0
> 2 2 1 0
>ect...
>I hope that all makes sense.
To be blunt - not at all.
Please post the structure of all relevant tables, as CREATE TABLE
statements. Don't forget to include all constraints, properties and
indexes. Then, post some illustrative sample rows of data (as INSERT
statements), one or two sample INSERT statements that should fire the
trigger and the end results you need to have in your table after the
trigger has finished execution. With that information, we can probably
help you write this trigger without cursors or temp tables.
Hugo Kornelis, SQL Server MVP|||Hugo,
Thanks for the response. What I'm looking do is actually quite easily
explain. I'll use 4 tables and three relationsip, Widgets (WidegetsID PK),
Colors(ColorsIDPK), Sizes(SizesID PK) and WidgetsUsed (WidgetsUsedID,
WidgetsID FK, ColorsID Fk, )
I do an insert of multiple widgets creating multiple rows which are stored
in the "Insert" Table of the trigger. When a new Widget is inserted I need
to initialize the WidgetsUsed table. This means inserting a new record for
each size and color possibility and setting . (This table will need a row fo
r
each color and size that widget can come in)
If 2 Widgets were added A and B, and the colors are stored in the colors
table, and the sizes are stored in the sizes table. For this example lets
say there are three color in the color table and two sizes in the color
table. So for each Widget inserted into the widget table I want to add 6
records into the Widgets used table. Finally I'll call the field in the
table I'm updating MyDataField.
I know the idea of using curosr is bad now and they they are very
inefficient, but what I was thinking was I would use the cursors like old
adodb recordsets and loop through each one like the procedure below. I thin
k
this is a pretty thourough description of what I'm doing. Thanks for your
effort.
CREATE TABLE [dbo].[tblWidgetsUsed](
[WidgetUsedID] [uniqueidentifier] NULL,
[WidgetID] [uniqueidentifier] NULL,
[ColorID] [uniqueidentifier] NULL,
[SizeID] [uniqueidentifier] NULL,
[WidgetsOrdered] [numeric](18, 0) NULL
) ON [PRIMARY]
CREATE PROCEDURE dbo.spTrigUtilInsert
-- Add the parameters for the stored procedure here
@.WidgetID as int = 0,
@.ColorId as int = 0,
@.SizeID as int = 0
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
Declare curWidget Cursor for
SELECT WidgetID FROM tblTemp --created from Insert in the trigger
open curWidget
fetch next from curWidget into @.WidgetID
--for each newly insertered record
while (@.@.Fetch_Status <> -1)
Declare curColor Cursor for SELECT ColorID FROM dbo.tblColor
open curColor
Fetch next from curColor into @.ColorID
-- For each Color
while (@.@.Fetch_Status <> -1)
-- Each Size
Declare curSize Cursor for SELECT DISTINCT SizeID FROM
dbo.tblSize
open curSize
fetch next from curSize into @.SizeID
While (@.@.Fetch_Status<>-1)
insert into tblWidgetsOrdered("WidgetID", "ColorID", "SizeID",
"NumOrdered")
Values (@.WidgetId, @.ColorID, @.SizeID, 0)
END
GO
Obviously these are not my real tables, because of security issues with my
project I can't use real tables but I think this show you what I'm looking t
o
do. I am using VS2005 Windows form (which is why I discuussed child and
parent tables, because I need to handle the insert order myself... I will
have a reply for the extreemly rude gent that is all high and mighty...)
Let me know what you think the way to do this is. I'm upgrading an access
based app to SQL Server 2005 and would like to take advantage of triggers to
initalize these rows. In the old applicaiton recordsets did the work.
Thanks again Hugo.
Greg P.
"Hugo Kornelis" wrote:
> On Tue, 9 May 2006 13:10:02 -0700, Greg P wrote:
>
> Hi Greg,
> First misunderstanding: you CAN declare anything in a trigger. Whoever
> told you otherwise obviously has little experience and even less
> knowledge of SQL Server.
> Second misunderstanding: Never ever use a cursor (*). And especially not
> inside a trigger. Unless you want to ruin your performance and your
> scalability, of course.
> (*) Okay, there are SOME situations where a cursor is the best choice,
> but they are very rare - only experienced DB programmers should be
> allowed to use cursors, because it takes a lot of experience to
> recognize a situation that might benefit from a cursor.
>
> If you MUST use the values from the inserted table in a stored
> procedure, then yes, you must copy the data from inserted to some other
> (preferably temporary) table.
> But I don't think that this is the correct solution in your case.
>
> To be blunt - not at all.
> Please post the structure of all relevant tables, as CREATE TABLE
> statements. Don't forget to include all constraints, properties and
> indexes. Then, post some illustrative sample rows of data (as INSERT
> statements), one or two sample INSERT statements that should fire the
> trigger and the end results you need to have in your table after the
> trigger has finished execution. With that information, we can probably
> help you write this trigger without cursors or temp tables.
> --
> Hugo Kornelis, SQL Server MVP
>|||For anyone else reading this please do not think I would ever speak this way
if it were not for the post this gentlemen made first.
Hey Genius,
Mr F&*%ing high and mighty... did you see the title of the post. I admitted
to being unfamiliar to using Triggers and Cursors and was looking for some
advice from this newsgroup. Your slam of a person who claims to be
unknowledgeable in topic shows absolute insecurity you informed prick. Yes
once again I will say you are more informed more than me about this, that’
s
why I’m asking the questions moron!!! You could explain nicely what issue
s
have yet I would have to charge you $150 an hour to be your psychologist
because I’m sure no one else want to talk to you and it still isn’t enou
gh
money to listen to your useless babble.
FYI, I have a degree in computer science and do understand RDBMS very
clearly. I have designed and implemented many solutions in many different
technologies. Now I’m learning to work with a new one, SQL Server 2005.
I know that when you update tables in VS2005 you need to handle the
add/mod/deletes yourself through typed datasets. These method must be calle
d
by hand and the terminology used for this process includes Parent, Child, an
d
Grandchild tables. Here is one link to such a reference in the updating
multiple tables section:
http://www.15seconds.com/issue/051123.htm
I also have a WROX’s Visual Basic 2005 Database Programming book in front
of
me, which is the “most advanced” book in this series which even has a di
agram
on page 173 discussing the use of Parent, Child and Grandchild insert, updat
e
and deletes.
So now I have to question what do you really know? It seems to me not much.
You can talk very loud and very rudely… yet not very intelligently. Pleas
e
do not lower the average IQ of my posts again with your “knowledge”.
Regards,
Greg P.
"--CELKO--" wrote:
> Stop using SQL and go back to a network database. You have described
> how they work as they build pointer chains as the data is inserted. I
> am not kidding -- read a DB history book. You even used the term
> "child" instead of "referenced" table!! Pure network/pointer chain
> database concepts and terms, not anything like RDBMS.
>
> Perhaps you should have read one book on RDBMS instead?
> You do not create a relational key. It already exists in the real
> world and you discover it.
> Triggers are a kludge for putting procedural code into a declarative
> language.
> You need to start over; you do not know what you are doing. People
> here will give you kludges to get rid of you quickly because we cannot
> give you a 1-2 year course in RDBMS. Telling someone to "smash rats
> with a rock when they get near your baby" is easier than "improve the
> sewer system by learning civil engineering so rats are not a problem"
> Look up this article: http://www.apa.org/journals/psp/psp7761121.html
> Journal of Personality and Social Psychology
> Unskilled and Unaware of It: How Difficulties in Recognizing One's Own
> Incompetence Lead to Inflated Self-Assessments
> Remember it takes SIX years to become a Union Journeyman Carpenter in
> New York State. How many years to be an SQL programmer? A few w
> in a ceritificate training class!
>|||Greg,
I dunno if this is what you want. And sorry for the delayed reply.. And
try to decipher this because I just got up from bed :)
try this...
create trigger trig1 on Widgets after insert
as
begin
insert into WidgetsUsed(WidgetID, ColorID, SizeID, NumOrdered)
select
a.WidegetsID,
b.colorsID,
c.sizesID,
0
from inserted a,
colors B,
sizes c
end
Let me know if this was what you wanted.
Newbee question about permissions and sp_OACreate
Hi,
I'm creating a trigger that shall monitor a table on inserts and if certain
conditions are met, it should send a mail the administrator.
I do not want to use SQLmail for many reasons so I'm using the extended
procedure sp_OACreate to create an instance of the CDO.Message object
The problem is that only sy
mins can use the extended procedure
sp_OACreate, and of cause I do not want users to be sy
mins.
I think I read or learned somewhere that stored procedures runs under the
security context of the user that created the procedure, so why can't I as
the sy
min create a my_sendmail procedure that uses the sp_OACreate
extended procedure and grant permission to all users to the my_sendmail
procedure?
Or, is there another way?
Regards,
Jorgen D.First of all, this excedes the purpose of triggers. What has sending mail go
t
to do with ACID? It would be much more efficient if you created a job to
monitor the table and log these special events in a separate table/file and
mail the report/warning.
Second, why is it not possible for you to use SQL Mail? It's far more
efficient than (ab)using sp_OA procedures. And it can be used by any user
without compromising the security.
How about notification services? If mailing these messages was requested by
a manager, you can be pretty sure, he'll start hating it after about a month
.
Either the messages will be too frequent or too infrequent and he'll still
need to keep statistics somewhere, somehow. But I'm just guessing here...
Anyway, seems to me that what you really need is some sort of logical event
logging. This IS the purpose of triggers - propagating changes in one table
to another.
Be careful out there...
ML|||Why do some people answer a question with more questions? (no, thanks for
your input)
My trigger do populate data to other tables (sending work orders to PDA’s,
via merge replication), and when done it’s important that the users
implicated (the ones that gets the work order) gets an mail/sms to inform
them about it (they should react to it immediately)
This mail shall originate form different senders, therefore not SQL-mail
which is based on a single profile (perhaps there is a way around that that
I
didn’t find)
Another reason not to use SQL-mail is in another scenario, that I’m not
going to explain in detail, but the mail should be HTML formatted report
larger than 8000 bytes.
Notification services? Hmmm, I’ll look into that, (as I don’t know what
that
is)
But to get back to my original question….. If I want to use an extended
procedure in my own procedure, how can I set permissions so the ordinary
mortal users can execute that?
Regards,
Jorgen D.
"ML" wrote:
> First of all, this excedes the purpose of triggers. What has sending mail
got
> to do with ACID? It would be much more efficient if you created a job to
> monitor the table and log these special events in a separate table/file an
d
> mail the report/warning.
> Second, why is it not possible for you to use SQL Mail? It's far more
> efficient than (ab)using sp_OA procedures. And it can be used by any user
> without compromising the security.
> How about notification services? If mailing these messages was requested b
y
> a manager, you can be pretty sure, he'll start hating it after about a mon
th.
> Either the messages will be too frequent or too infrequent and he'll still
> need to keep statistics somewhere, somehow. But I'm just guessing here...
> Anyway, seems to me that what you really need is some sort of logical even
t
> logging. This IS the purpose of triggers - propagating changes in one tabl
e
> to another.
> Be careful out there...
>
> ML|||Any user who needs to execute sp_OA procedures must have appropriate
privileges to do so.
I'm sorry, I'm simply curious as to what you're trying to do. You say
certain users must be notified (with a large report, even) of certain change
s
to yor data. And this must be done immediately after those changes were
commited. Why? Do this users then do something? Couldn't that be done
automatically?
It's like in that nuclear plant: "push this button when that light goes on"
- why not just automatically do whatever the button does when conditions are
met which normally tur the light on...?
Instead of sending huge reports you could simply send a link to the report
built by the SQL Reporting Services.
Consider the alternatives before you compromise security.
ML|||Some users are security guards which have to respond to alarms. When they ge
t
notified they should turn on their PDA and connect to the server to get
detailed information of the alarm (address, codes etc.). Other users are
doing emergency road help. So the notification is important to be timely.
They can’t ask the server/system to drive to an incident.
About the reports – They aren’t huge. A single HTML formatted page (tabl
es,
and colours) is larger than 8K which is the limit of SQL-mail, further more
I
can’t get SQL-mail to send in HTML. The reports are requested from the use
rs
PDA to be sent to the customers email. The reports are dynamically created o
n
the server and can’t be sent from the PDA (they don’t have the data)
Conclusion: Since I have to use CDO.Message I have to grant all users public
access to the master database, and then on the sp_OAxxxxx procedures, give
the users EXEC rights. What happened to the ideology “The code of a stored
procedure runs within the security context of the creator”?
"JorgenD" wrote:
> Why do some people answer a question with more questions? (no, thanks for
> your input)
> My trigger do populate data to other tables (sending work orders to PDA’
s,
> via merge replication), and when done it’s important that the users
> implicated (the ones that gets the work order) gets an mail/sms to inform
> them about it (they should react to it immediately)
> This mail shall originate form different senders, therefore not SQL-mail
> which is based on a single profile (perhaps there is a way around that tha
t I
> didn’t find)
> Another reason not to use SQL-mail is in another scenario, that I’m not
> going to explain in detail, but the mail should be HTML formatted report
> larger than 8000 bytes.
> Notification services? Hmmm, I’ll look into that, (as I don’t know wha
t that
> is)
> But to get back to my original question….. If I want to use an extended
> procedure in my own procedure, how can I set permissions so the ordinary
> mortal users can execute that?
> Regards,
> Jorgen D.
>
> "ML" wrote:
>|||You're describing a messaging and reporting system for which web services ar
e
the ideal solution. You have a central data server or a data warehouse and
several clients, that aren't capable of maintaining a 24/7 connection to HQ.
Wouldn't it be more efficient if the clients would only receive short
messages, rather than full reports? Upon the notification they could then
connect to the Report server to see the details of the arising situation and
then decide if they need to download them for off-line use.
That way you can allow access to the same data to the PDA users and to the
desktop users.
You might end up developing a messaging and reporting system using
webservices and smart clients. You could even earn $50 grand!!! :)
(http://www.csdevcompetition.com/)
Giving master database/extended procedure privileges to the Public role is a
bad idea. It is IMHO essential to use a custom role for this - with
explicitly limited privileges.
Also consider the fact that your inserts might slow down due to the needed
complexity of these triggers - that is if the conditions are met frequently.
Of course you'll need a lot of error-handling as well - you don't want to
lock up the server, do you?
ML|||Hi
Look at SQL Server Notification Services to kick of a process where you have
a .NET application send the mail via SMTP.
If you kick off an sp_OA* within a trigger, and it fails, you end up having
a rolled back transaction, possible some e-mails being sent about data that
no longer exists.
If you do not want to use NS, then in your trigger, write a row to another
table indicate that something must be done, and then have SQL Server Agent
process poll the table and send the e-mail.
Regards
--
Mike Epprecht, Microsoft SQL Server MVP
Zurich, Switzerland
MVP Program: http://www.microsoft.com/mvp
Blog: http://www.msmvps.com/epprecht/
"ML" wrote:
> You're describing a messaging and reporting system for which web services
are
> the ideal solution. You have a central data server or a data warehouse and
> several clients, that aren't capable of maintaining a 24/7 connection to H
Q.
> Wouldn't it be more efficient if the clients would only receive short
> messages, rather than full reports? Upon the notification they could then
> connect to the Report server to see the details of the arising situation a
nd
> then decide if they need to download them for off-line use.
> That way you can allow access to the same data to the PDA users and to the
> desktop users.
> You might end up developing a messaging and reporting system using
> webservices and smart clients. You could even earn $50 grand!!! :)
> (http://www.csdevcompetition.com/)
>
> Giving master database/extended procedure privileges to the Public role is
a
> bad idea. It is IMHO essential to use a custom role for this - with
> explicitly limited privileges.
> Also consider the fact that your inserts might slow down due to the needed
> complexity of these triggers - that is if the conditions are met frequentl
y.
> Of course you'll need a lot of error-handling as well - you don't want to
> lock up the server, do you?
>
> ML
I'm creating a trigger that shall monitor a table on inserts and if certain
conditions are met, it should send a mail the administrator.
I do not want to use SQLmail for many reasons so I'm using the extended
procedure sp_OACreate to create an instance of the CDO.Message object
The problem is that only sy
sp_OACreate, and of cause I do not want users to be sy
I think I read or learned somewhere that stored procedures runs under the
security context of the user that created the procedure, so why can't I as
the sy
extended procedure and grant permission to all users to the my_sendmail
procedure?
Or, is there another way?
Regards,
Jorgen D.First of all, this excedes the purpose of triggers. What has sending mail go
t
to do with ACID? It would be much more efficient if you created a job to
monitor the table and log these special events in a separate table/file and
mail the report/warning.
Second, why is it not possible for you to use SQL Mail? It's far more
efficient than (ab)using sp_OA procedures. And it can be used by any user
without compromising the security.
How about notification services? If mailing these messages was requested by
a manager, you can be pretty sure, he'll start hating it after about a month
.
Either the messages will be too frequent or too infrequent and he'll still
need to keep statistics somewhere, somehow. But I'm just guessing here...
Anyway, seems to me that what you really need is some sort of logical event
logging. This IS the purpose of triggers - propagating changes in one table
to another.
Be careful out there...
ML|||Why do some people answer a question with more questions? (no, thanks for
your input)
My trigger do populate data to other tables (sending work orders to PDA’s,
via merge replication), and when done it’s important that the users
implicated (the ones that gets the work order) gets an mail/sms to inform
them about it (they should react to it immediately)
This mail shall originate form different senders, therefore not SQL-mail
which is based on a single profile (perhaps there is a way around that that
I
didn’t find)
Another reason not to use SQL-mail is in another scenario, that I’m not
going to explain in detail, but the mail should be HTML formatted report
larger than 8000 bytes.
Notification services? Hmmm, I’ll look into that, (as I don’t know what
that
is)
But to get back to my original question….. If I want to use an extended
procedure in my own procedure, how can I set permissions so the ordinary
mortal users can execute that?
Regards,
Jorgen D.
"ML" wrote:
> First of all, this excedes the purpose of triggers. What has sending mail
got
> to do with ACID? It would be much more efficient if you created a job to
> monitor the table and log these special events in a separate table/file an
d
> mail the report/warning.
> Second, why is it not possible for you to use SQL Mail? It's far more
> efficient than (ab)using sp_OA procedures. And it can be used by any user
> without compromising the security.
> How about notification services? If mailing these messages was requested b
y
> a manager, you can be pretty sure, he'll start hating it after about a mon
th.
> Either the messages will be too frequent or too infrequent and he'll still
> need to keep statistics somewhere, somehow. But I'm just guessing here...
> Anyway, seems to me that what you really need is some sort of logical even
t
> logging. This IS the purpose of triggers - propagating changes in one tabl
e
> to another.
> Be careful out there...
>
> ML|||Any user who needs to execute sp_OA procedures must have appropriate
privileges to do so.
I'm sorry, I'm simply curious as to what you're trying to do. You say
certain users must be notified (with a large report, even) of certain change
s
to yor data. And this must be done immediately after those changes were
commited. Why? Do this users then do something? Couldn't that be done
automatically?
It's like in that nuclear plant: "push this button when that light goes on"
- why not just automatically do whatever the button does when conditions are
met which normally tur the light on...?
Instead of sending huge reports you could simply send a link to the report
built by the SQL Reporting Services.
Consider the alternatives before you compromise security.
ML|||Some users are security guards which have to respond to alarms. When they ge
t
notified they should turn on their PDA and connect to the server to get
detailed information of the alarm (address, codes etc.). Other users are
doing emergency road help. So the notification is important to be timely.
They can’t ask the server/system to drive to an incident.
About the reports – They aren’t huge. A single HTML formatted page (tabl
es,
and colours) is larger than 8K which is the limit of SQL-mail, further more
I
can’t get SQL-mail to send in HTML. The reports are requested from the use
rs
PDA to be sent to the customers email. The reports are dynamically created o
n
the server and can’t be sent from the PDA (they don’t have the data)
Conclusion: Since I have to use CDO.Message I have to grant all users public
access to the master database, and then on the sp_OAxxxxx procedures, give
the users EXEC rights. What happened to the ideology “The code of a stored
procedure runs within the security context of the creator”?
"JorgenD" wrote:
> Why do some people answer a question with more questions? (no, thanks for
> your input)
> My trigger do populate data to other tables (sending work orders to PDA’
s,
> via merge replication), and when done it’s important that the users
> implicated (the ones that gets the work order) gets an mail/sms to inform
> them about it (they should react to it immediately)
> This mail shall originate form different senders, therefore not SQL-mail
> which is based on a single profile (perhaps there is a way around that tha
t I
> didn’t find)
> Another reason not to use SQL-mail is in another scenario, that I’m not
> going to explain in detail, but the mail should be HTML formatted report
> larger than 8000 bytes.
> Notification services? Hmmm, I’ll look into that, (as I don’t know wha
t that
> is)
> But to get back to my original question….. If I want to use an extended
> procedure in my own procedure, how can I set permissions so the ordinary
> mortal users can execute that?
> Regards,
> Jorgen D.
>
> "ML" wrote:
>|||You're describing a messaging and reporting system for which web services ar
e
the ideal solution. You have a central data server or a data warehouse and
several clients, that aren't capable of maintaining a 24/7 connection to HQ.
Wouldn't it be more efficient if the clients would only receive short
messages, rather than full reports? Upon the notification they could then
connect to the Report server to see the details of the arising situation and
then decide if they need to download them for off-line use.
That way you can allow access to the same data to the PDA users and to the
desktop users.
You might end up developing a messaging and reporting system using
webservices and smart clients. You could even earn $50 grand!!! :)
(http://www.csdevcompetition.com/)
Giving master database/extended procedure privileges to the Public role is a
bad idea. It is IMHO essential to use a custom role for this - with
explicitly limited privileges.
Also consider the fact that your inserts might slow down due to the needed
complexity of these triggers - that is if the conditions are met frequently.
Of course you'll need a lot of error-handling as well - you don't want to
lock up the server, do you?
ML|||Hi
Look at SQL Server Notification Services to kick of a process where you have
a .NET application send the mail via SMTP.
If you kick off an sp_OA* within a trigger, and it fails, you end up having
a rolled back transaction, possible some e-mails being sent about data that
no longer exists.
If you do not want to use NS, then in your trigger, write a row to another
table indicate that something must be done, and then have SQL Server Agent
process poll the table and send the e-mail.
Regards
--
Mike Epprecht, Microsoft SQL Server MVP
Zurich, Switzerland
MVP Program: http://www.microsoft.com/mvp
Blog: http://www.msmvps.com/epprecht/
"ML" wrote:
> You're describing a messaging and reporting system for which web services
are
> the ideal solution. You have a central data server or a data warehouse and
> several clients, that aren't capable of maintaining a 24/7 connection to H
Q.
> Wouldn't it be more efficient if the clients would only receive short
> messages, rather than full reports? Upon the notification they could then
> connect to the Report server to see the details of the arising situation a
nd
> then decide if they need to download them for off-line use.
> That way you can allow access to the same data to the PDA users and to the
> desktop users.
> You might end up developing a messaging and reporting system using
> webservices and smart clients. You could even earn $50 grand!!! :)
> (http://www.csdevcompetition.com/)
>
> Giving master database/extended procedure privileges to the Public role is
a
> bad idea. It is IMHO essential to use a custom role for this - with
> explicitly limited privileges.
> Also consider the fact that your inserts might slow down due to the needed
> complexity of these triggers - that is if the conditions are met frequentl
y.
> Of course you'll need a lot of error-handling as well - you don't want to
> lock up the server, do you?
>
> ML
Labels:
administrator,
certainconditions,
creating,
database,
inserts,
mail,
met,
microsoft,
monitor,
mysql,
newbee,
oracle,
permissions,
server,
shall,
sp_oacreate,
sql,
table,
trigger
Newb with a serious Trigger question.
Ok I am stumped. I am a newbie in terms of triggers and procedures and am
used to writing inline sql statements , so here is my situation.
I have an audit table for all the updates , inserts and deletes throughout
one of my application database(SQL2005).
Whenever something happens a record gets inserted into this table(this was
all accomplished by an external dll coded somewhere else that i found on the
internet - and all this works fantastically.)
The problem i have is that after the insert into the audit table occurs, i
want to be able to do this...
have a second trigger for the insert on the audit table
this will go out using the Primary key of the edited table (eg. tasks) and
the table name (eg tasks_) and operation type (eg UPDATE< INSERT whatever)
and get these values that are now in the new audit table record.
then i want to use these values to dynamically select a created_By field
from say the tasks table and update the audit record with this new
created_By field.
the theory is that the dll works but puts dbo in for the user all the time,
so i want to go into the application side and grab the user who entered the
info and update the audit trail records.
Is this clear and concise or am i mumbling?
Any help would be vastly appreciated.
Thanks in advance,
COlinColin Smart (csmart@.nf.sympatico.ca) writes:
> I have an audit table for all the updates , inserts and deletes throughout
> one of my application database(SQL2005).
> Whenever something happens a record gets inserted into this table(this was
> all accomplished by an external dll coded somewhere else that i found on
> the internet - and all this works fantastically.)
> The problem i have is that after the insert into the audit table occurs, i
> want to be able to do this...
> have a second trigger for the insert on the audit table this will go out
> using the Primary key of the edited table (eg. tasks) and the table name
> (eg tasks_) and operation type (eg UPDATE< INSERT whatever) and get
> these values that are now in the new audit table record.
> then i want to use these values to dynamically select a created_By field
> from say the tasks table and update the audit record with this new
> created_By field.
> the theory is that the dll works but puts dbo in for the user all the
> time, so i want to go into the application side and grab the user who
> entered the info and update the audit trail records.
From exactly where is this DLL invoked?
This sounds like a solution for SQL 2000 or earlier. That trigger
would be messy to code. It sounds as if the DLL runs as dbo, in
which case you could use dynamic SQL. But if any of the tables does
not have a Created_by column, it will bloe up at run-time. A better
solution would be to pass the DLL the value of original_login() somehow.
(On SQL 2005 you should use original_login(), rather than SYSTEM_USER.)
On SQL 2005, the xml column can be very good for auditing. It depends
exactly what you will use the audit data for, but if you are not going
to run any searches on other data than the table name and key values,
you can use an xml column. The nice thing is that you can do a
SELECT ... FROM inserted FOR XML, and the triggers can be quite generic.
Even nicer is that you can make an entire generic program that reads
the log table, and presents the differences between two log records.
If you insert directly into the auditlog, there is not any problem of
retrieving the current user.
Erland Sommarskog, SQL Server MVP, esquel@.sommarskog.se
Books Online for SQL Server 2005 at
http://www.microsoft.com/technet/pr...oads/books.mspx
Books Online for SQL Server 2000 at
http://www.microsoft.com/sql/prodin...ions/books.mspx
used to writing inline sql statements , so here is my situation.
I have an audit table for all the updates , inserts and deletes throughout
one of my application database(SQL2005).
Whenever something happens a record gets inserted into this table(this was
all accomplished by an external dll coded somewhere else that i found on the
internet - and all this works fantastically.)
The problem i have is that after the insert into the audit table occurs, i
want to be able to do this...
have a second trigger for the insert on the audit table
this will go out using the Primary key of the edited table (eg. tasks) and
the table name (eg tasks_) and operation type (eg UPDATE< INSERT whatever)
and get these values that are now in the new audit table record.
then i want to use these values to dynamically select a created_By field
from say the tasks table and update the audit record with this new
created_By field.
the theory is that the dll works but puts dbo in for the user all the time,
so i want to go into the application side and grab the user who entered the
info and update the audit trail records.
Is this clear and concise or am i mumbling?
Any help would be vastly appreciated.
Thanks in advance,
COlinColin Smart (csmart@.nf.sympatico.ca) writes:
> I have an audit table for all the updates , inserts and deletes throughout
> one of my application database(SQL2005).
> Whenever something happens a record gets inserted into this table(this was
> all accomplished by an external dll coded somewhere else that i found on
> the internet - and all this works fantastically.)
> The problem i have is that after the insert into the audit table occurs, i
> want to be able to do this...
> have a second trigger for the insert on the audit table this will go out
> using the Primary key of the edited table (eg. tasks) and the table name
> (eg tasks_) and operation type (eg UPDATE< INSERT whatever) and get
> these values that are now in the new audit table record.
> then i want to use these values to dynamically select a created_By field
> from say the tasks table and update the audit record with this new
> created_By field.
> the theory is that the dll works but puts dbo in for the user all the
> time, so i want to go into the application side and grab the user who
> entered the info and update the audit trail records.
From exactly where is this DLL invoked?
This sounds like a solution for SQL 2000 or earlier. That trigger
would be messy to code. It sounds as if the DLL runs as dbo, in
which case you could use dynamic SQL. But if any of the tables does
not have a Created_by column, it will bloe up at run-time. A better
solution would be to pass the DLL the value of original_login() somehow.
(On SQL 2005 you should use original_login(), rather than SYSTEM_USER.)
On SQL 2005, the xml column can be very good for auditing. It depends
exactly what you will use the audit data for, but if you are not going
to run any searches on other data than the table name and key values,
you can use an xml column. The nice thing is that you can do a
SELECT ... FROM inserted FOR XML, and the triggers can be quite generic.
Even nicer is that you can make an entire generic program that reads
the log table, and presents the differences between two log records.
If you insert directly into the auditlog, there is not any problem of
retrieving the current user.
Erland Sommarskog, SQL Server MVP, esquel@.sommarskog.se
Books Online for SQL Server 2005 at
http://www.microsoft.com/technet/pr...oads/books.mspx
Books Online for SQL Server 2000 at
http://www.microsoft.com/sql/prodin...ions/books.mspx
Subscribe to:
Posts (Atom)