Trigger Problem With Sp_send_dbmail

May 15, 2008

Hallo

I want to write a trigger that sends me an email, when new records are added into a table.

For testing I have created one table called location1, which has simple data from AdventureWorks.Production.Location. And another table is called new_location, which stores the newly added records.

Here is the trigger:********************************
use [AdventureWorks]
if object_id ('location1') is not null
drop table location1
go
create table location1(LocationID int, LName varchar(50))

if object_id ('new_location') is not null
drop table new_location
go
create table new_location
(LocationID int, LName varchar(50))

if object_id ('change_ID', 'TR') is not null
drop trigger change_ID
go
create trigger change_ID on location1
for insert
as
delete new_location
insert into new_location
select * from inserted

exec sp_send_dbmail
@profile_name = 'Profile',
@recipients = 'email',
@subject = 'New Record(s) added.',
@query = 'select * from new_location order by LocationID';
go
********************************

After I insert statement, Management Studio runs the executing throughout.
insert into location1
select LocationID, Name
from Production.Location
order by LocationID

Can somebody help?









View 2 Replies


ADVERTISEMENT

Sp_send_dbmail Trigger On Multiple Row Insert

Feb 15, 2008

Hi,


I have a SQL Agent Job that selects records that are of a particular age (from Table1) and inserts them into another table (Table 2) - multiple records get inserted as a single INSERT step. On Table 2 I then have a trigger set FOR INSERT which I was hoping would send an email using the fields copied from the batch job, one of which being an email address.


The trigger is: -




Code Snippet
CREATE TRIGGER trgSendMail ON Table2 FOR INSERT AS
DECLARE @myEmail VarChar(50)
SELECT @myEmail = strEmail FROM Inserted
EXEC sp_send_dbmail
@Profile_Name = '{MailProfile}',
@Recipients = @myEmail,
@Subject = '{MailTitle}',
@Body = '{MailBody}'






Thing is, the agent works fine but the trigger only sends an email to the first row inserted.
Any ideas on how to get around this so that if the batch job inserts 10 rows into Table2 then 10 emails are sent out?

Shaun.

View 6 Replies View Related

Sp_send_dbmail

May 9, 2006

When using "sp_send_dbmail", messages are queued through Service Broker. Other than the system views, "dbo.sysmail_...", in MSDB, is there another way to know if an email was sent successfully?

Also, in 2000 you did not need to supply the whole email address in order for xp_sendmail to work. For example, I could use my name, "RGioia" as the recipient and it would send email to rgioia@<my current domain>. Does anyone know of a work-around for this in 2005 or do you just have to ensure that full email addresses are used?

Thanks in advance!!

View 1 Replies View Related

SP_SEND_DBMAIL

Aug 8, 2007

I wrote a trigger as follows:

CREATE TRIGGER TR_ABC
ON TABLE_A
AFTER INSERT
AS
DECLARE @E_MAIL VARCHAR(255),
@MESSAGE VARCHAR(255)
SET @MESSAGE = 'A new call request has been logged'

SELECT @E_MAIL = E_MAIL
FROM TABLE_A AS A
LEFT OUTER JOIN TABLE_B AS B
ON B.SYSADMIN = A.SYSADMIN
WHERE SYS_ADMIN = 1

EXEC MSDB.DBO.SP_SEND_DBMAIL
@profile_name = 'SCINFO',
@recipients = @E_MAIL,
@body = @MESSAGE,
@subject = 'SCI Service Request';


The problem is everytime I insert data into the table I get an error stating that-:
'At least one of the following parameters must be specified. "@recipients, @copy_recipients, @blind_copy_recipients".
Mail queued.'

Please help.

View 1 Replies View Related

Need Help W/ Sp_send_dbmail !

May 1, 2007

SQL Server 2005Help. I have a problem:On a 2000 box, I am calling the sp_send_dbmail stored procedure on a2005 box (they are linked servers).This is how I'm calling the proc (from the 2000 box), which usessp_send_dbmail to send the mail.EXEC My2005Server.DatabaseName.dbo.SendNotification@recipients = 'me@yahoo.com',@subject = 'SENDING @TOTAL,@body = @text1 + @text2 + @text3 + @text4 + @text5@text1 - @text5 are varchar(8000).As you can see I'm trying to take advantage of the varchar(max) that@body allows.However, I get this error:Server: Msg 170, Level 15, State 1, Line 22Line 22: Incorrect syntax near '+'.I need to be able to concatenate these somehow... as I cannot put theminto one large variable from the 2000 server side.Can you see the problem here?Help.Thanks

View 1 Replies View Related

Sp_send_dbmail

Oct 31, 2007

Hello all,

I'm new to this forum and have the same question on SQLTeam.com, where I'm a frequent forum user.

I'm trying to send the results of a table to a group of people by email, see code used below:

exec msdb.dbo.sp_send_dbmail @profile_name = 'DT', @recipients = 'isantos@foo.net;', @subject = 'QA Results', @body = 'Some Text', @query = 'select * from [db].[dbo].[table]', @execute_query_database = 'db', @exclude_query_output = 1, @append_query_error = 1;


Error message I get by email:

Msg 15404, Level 16, State 19, Server TAKKARA, Line 1 Could not obtain information about Windows NT group/user 'WECLICKisantos', error code 0x5.

If I remove the @query, @exclude_query_output and @append_query_error options, I can send the email without a problem, just whenever I try to add a query to it that it gives me this error message.

I'm a sysadmin, I can run that query, I have access to the DatabaseMailUserRole under msdb and the profile that I'm using is public... I'm kind of stuck, let me know if you can help.

View 3 Replies View Related

Sp_send_dbmail Question

Apr 14, 2008

I'm running the following test

declare @dbccdate varchar(60)
set @dbccDate='dbcc east' + convert(varchar(60),getdate(),10)
exec msdb.dbo.sp_send_dbmail
@recipeints='human@gmail.com',
@body = 'This is a test'
@subject= @dbccdate ,
@query='dbcc checkdb (msdb)',
@attach_query_result_as_file=1,
@query_attachment_filename='Dbcc_MSDB_Results.txt'

This works fine but, I'd really like the subject to contain the line
"Checkdb found 0 errors..." So mgmt doesn't have to open the txt file to view the results.

I've tried dumping the results to a txt file first. Then trying to read the text file for the line inquestion. I wrote a for loop to parse the results command line, but can't figure how to add that value to the subject.

The script is this:

for /f %i in ('findstr /B /I "CHECKDB" y:dbcclogmsdblog.txt') do echo %i

Is there anyway to do this?

View 5 Replies View Related

Possible Issues With SP2 And Sp_send_dbmail?

Apr 25, 2007

Have a funny one that I've not yet resolved, and was wondering if I am the only one.

SQL2005 SP1 server, Ent Ed, 64 bit, clustered machine.
SP2a installed over Easter weekend.

about 12 days after apparently succesful upgrade, the cluster was failed over. After that fail-over, an existing job started failing, with the following message:
quote:Error executing extended stored procedure: Invalid Parameter [SQLSTATE 42000] (Error 22050). The step failed.

All the job does is build a SQL query, then supply the query to sp_send_dbmail for execution:

DECLARE
@RetCodebit,
@Tovarchar(200),
@Subjectvarchar(100),
@CCvarchar(200),
@Queryvarchar(max),
@Debugsmallint

--cut section that has the query , but these are straight SQL
--queries - no SP or XP usage whatsoever

EXEC@RetCode = msdb.dbo.sp_send_dbmail
@profile_name= 'Email',
@recipients= @To,
@subject= @Subject,
@copy_recipients= @CC,
@query_result_header=0,
@Query=@Query

One 'funny' I noticed is that up until the failover, SSMS seemed to erport the version of the server as still the SP1 (2157). After failover, it now lists (3042). This may simply be a symptom of SSMS not auto-refreshing though. We have (I believe) failed back again since then, still no joy.

Any Ideas?

*##* *##* *##* *##*
Chaos, Disorder and Panic ... my work is done here!

View 5 Replies View Related

Sp_send_dbmail Problem

Feb 26, 2008

I am trying to use the sp_send_dbmail sproc but I get the following error:

Msg 22051, Level 16, State 1, Line 0
Attachment file C: est.txt is invalid.

My code:


EXEC msdb.dbo.sp_send_dbmail
@profile_name = 'SQL Server Mail Profile blah blah',
@recipients = 'myEmail@somewhere.com,
@body = 'Hello World',
@subject = 'Hello World',
@file_attachments = N'C: est.txt'

why would that be? The test.txt file does exist on my drive!

Please advise.

View 9 Replies View Related

Sp_send_dbmail Without Using A Cursor?

Aug 22, 2007

I have a table which contains a list of addresses to send an email to. I'd like to be able to do something like:


update emaillist

set sendcount = SendMyMessage( emailaddress )
where sendcount = 0


In this case SendMyMessage is a user defined function which calls the sp_send_dbmail stored procedure.

However, I am receiving an error saying "Only functions and extended stored procedures can be executed from within a function"


From what I've seen, it sounds like I am forced to use a cursor to go through my email list table. Is that the only way?

Under SQL 2000, using a user defined function to call CDONTS was a no brainer....



Thanks,
Chris.

View 3 Replies View Related

Sp_send_dbmail &&amp; COM Errors.

Mar 23, 2006

I just started getting these errors on a few (not all) servers the other day. These servers have been running fine for a few months now...



Msg 14661, Level 16, State 1, Procedure sp_send_dbmail, Line 476

Query execution failed: Error initializing COM

Msg 0, Level 11, State 0, Line 0

A severe error occurred on the current command. The results, if any, should be discarded.



I can only find one thread regarding this error, specifically with dbmail and I am doing the same thing (executing a query and attaching the results).

http://www.sqlservercentral.com/forums/shwmessage.aspx?forumid=149&messageid=248650

This thread points to a KB article http://support.microsoft.com/kb/910416 which is close except for the fact that these were not upgrades, but clean installs. I'm leary of applying the hotfix to my servers.

Is this a known issue internal to MS and is the referenced hotfix appropriate to install?

View 8 Replies View Related

Sp_send_dbmail Possible Security Issue

May 28, 2008

I have a stored procedure that sends an mail using sp_send_dbmail. My problem is, if I execute the stored procedure via my ASP.NET 2005 application, the email will not send. I know the stored procedure is being called and works because:
1. The stored procedure does 2 things, sets a status, then sends the email. The status is being changed, but the email is not being sent.
2. When I investigate with Sql Server Profiler, I see the stored proc being called and the values of the parameters are set as they should be.
What I don't understand is, I can copy the call in Sql Server Profler, and paste it in a Query Analyzer window and execute that same call, and everything works fine, status is changed, and the email is sent (to myself for testing and I receive it just fine).
Is there a reason why the email won't send via code? Am I suppose to setup some security that will allow my application to send emails? Any info would be GREATLY appreciated.

View 2 Replies View Related

Problem With Sp_send_dbmail With Attachment

Aug 2, 2007

Hi,

We have a DTS package in the old SS2000 that we are still using in SS2005. We change the old xp_sendmail to use the new sp_send_dbmail. This runs fine without attachment. But with attachment, I'm encountering an error when running the package.

The task reported failure on execution.
The client connection security context could not be impersonated. Attaching file requires an integrated client login.
Syntax error or access violation.

I cannot find much topic on the net about this error.

Thanks very much for any help.

Regards

View 1 Replies View Related

Sql 2005, Sp_send_dbmail, @profile_name

Jan 23, 2008

Hi everyone,
I'm trying to usie "sp_send_dbmail" and i'm required to provide value to: "@profile_name" argument. The trouble is i have no idea what it means..
How do i get to know what is my "profile_name" ?
Thanks.

View 1 Replies View Related

Msdb.dbo.sp_send_dbmail Error

Feb 28, 2007

I make PROCEDURE to send email useing db msdb and this PROCEDURE dbo.sp_send_dbmail like this

EXEC msdb.dbo.sp_send_dbmail

@profile_name = 'saly',

@recipients = @email,

@subject = @subject,

@body = @body;

Go

And when EXEC it gives me mail qeue

and mail don't arrive where it goes i don't know please tell me what error

thankx very much

View 9 Replies View Related

Sp_send_dbmail Erroring Out On Line 476?!

Dec 5, 2007



Hello all -

I'm using SQL Server 2005. I'm trying to send an email with query results attached.
I've enabled database mail (surface config, config wizard, profile set, accounts loaded).
I know database mail itself works as I'm able to send plain text messages as well as messages with HTML embedded.
However, when I try to format a query to send attachments with mail, as shown in BOL; I always get this error message -
<snip>

Msg 14661, Level 16, State 1, Procedure sp_send_dbmail, Line 476

Query execution failed: Error initializing COM

Msg 0, Level 11, State 0, Line 0

A severe error occurred on the current command. The results, if any, should be discarded.
<snip>

Here is a sample of the query...

DECLARE @WHO VARCHAR(255)

SET @WHO = '<name would go here>'

EXEC msdb.dbo.sp_send_dbmail

@profile_name = 'sqlmail'

,@recipients = 'my.name@wouldgohere.com'

,@subject = 'testing attachment'

,@query = N'SELECT email_body

FROM WFS_non_stock_email_sendit_history

WHERE who_entered = @WHO

ORDER BY date_created DESC

OPTION(MAXDOP 1)'

,@execute_query_database = 'whaley'

,@attach_query_result_as_file = 1

,@query_attachment_filename = 'TESTATTACH.txt'

,@query_result_separator = ';'

If I were to run this query outside of this dbmail code, the query works fine.

If I can believe the go to line editor, line 476 in the sp_send_dbmail sproc is...

DELETE sysmail_attachments_transfer WHERE uid = @temp_table_uid


My problem here is this is a system sproc that MSFT built. I don't understand why I would get this error message instead of something more definitive and indicative of the problem.

Has anyone else seen this problem? I really need to be able to send attachments.

Thanks

Randyvol

View 1 Replies View Related

Sp_send_dbmail Doesn't Work

Jan 17, 2008

hi all,
i made a stored procedure that uses the sp_send_dbmail to send mails. SQL server dislays the message "mail queued" but nothing is recieved

here is the code of the stored procedure i made
EXEC msdb.dbo.sp_send_dbmail
@profile_name = 'Exams',
@recipients = 'me@domain.com',
@Body_format = 'HTML' ,
@subject = 'Room Preparation' ,
@body='hi there';
so can anyone help with this issue
thanks in advance

View 6 Replies View Related

Sp_send_dbmail Query Option

Sep 22, 2007

Hello,
I'm using sp_send_dbmail with query option. Is there a way to not have "1 rows returned" in the email?
Thanks!

View 3 Replies View Related

Sp_send_dbmail Result Header

May 15, 2007

I am trying to use sp_send_dbmail to exec stored procedure results to an email as an attachement. This works very well, except for one problem, it is not giving the result headers for the queries in the stored procedure even with the

@query_result_header = 1



I have also tried this with a VERY simple query, just incase it was the multiple result sets causing the problem, also not putting the results as an attachment and just straight into the body.



Does anybody know how to solve this problem?



Thanks in advance,



Chris

View 2 Replies View Related

Sp_send_dbmail. How Can I Use A Query For @recipients

Feb 5, 2008

Hi everyone,
i'd like to assign "@recipients" for sp_send_dbmail derived from a query as follows:



Code SnippetDECLARE @mailist VARCHAR(2000)
SET @mailist=
'select email
from
server.db.dbo.table
where
lastname=' +''''+'aaa'+''''
exec msdb.dbo.sp_send_dbmail
@profile_name='myprofile',
@recipients=@mailist,
@subject='email address through a query',
@...



when i run it i dont get any error message but mails to dot arrive.
any suggestion why ?
Thanks a lot

View 5 Replies View Related

Attach Query Results As Xml With SP_SEND_DBMAIL

Jun 10, 2008

I'm trying to get sp_send_dbmail to attach the @query result set as an xml file.

The email is being sent and the attachment is present, but rather than ascii xml, it contains a chunk of nonsense like this
0x440352004F005700440470006B00650079004409660069007200730074006E0061006D00650044086C006100730074006E0061006D0065004410700068

I've tested the query with the first bit of code and sent the email with the second bit. I think I can jimmyjack it to write the xml to a temp file on the server and send that file using the @file_attachments parameter, but I'm hoping someone out there knows how to get this one to work.

Thanks in advance for any help you can give me.

Here's my code:


-- test that xml output is being generated
DECLARE @OUTPUT xml
SET @OUTPUT = (SELECT * FROM database..table FOR XML PATH('ROW'), root('ROOT'))
SELECT @OUTPUT

-- run the email proc
EXEC msdb.dbo.sp_send_dbmail
@QUERY= 'SET NOCOUNT ON SELECT * FROM database..table FOR XML PATH(''ROW''), root(''ROOT'')'
,@RECIPIENTS= 'userid@companyname.COM'
,@subject= 'Subject'
,@attach_query_result_as_file= 1
,@query_attachment_filename= 'ATTACHMENT.xml'
,@query_result_width= 32767
,@query_no_truncate= 1
,@append_query_error= 1
,@query_result_header= 1

View 2 Replies View Related

Sp_send_dbmail-Mail Not Sent - Remote Certificate

Oct 17, 2007

When i use sp_send_dbmail stored procedure inside a Execute SQL task,the task is executed successfully.

But when i look in to 'Database Mail Log', it says

"The mail could not be sent to the recepient because of the mail server failure. Exception message: cannot send mails to mail server(The remote certificate is invalid according to the validation procedure)

Please let me know what can be the issue.

View 2 Replies View Related

Sql Server 2005 How Do I Turn On Sp_send_dbmail

Feb 18, 2008

Hi everyone.
I've just installed sql server 2005 (evaluation) and i need to turn the option of using sp_send_dbmail on. I tried books on line but didnt manage to understand how it is done.
Thanks

View 5 Replies View Related

Sp_send_dbmail Mail Queued. Message

May 2, 2006

I have an After Update Trigger specified on a database table to notify specific users via email when certain customer values are modified. (This is a HACK / Workaround for functionality that doesn't exsist in the product.)

I had be using xp_sendmail without a problem. I recently upgraded the database server to SQL2005 and wanted to try sp_send_dbmail. (I was interested in the asynch and the non-MAPI nature of Database Mail.)

This is the new code:


EXEC @retval = msdb.dbo.sp_send_dbmail


@recipients = @rec,

@blind_copy_recipients = @bcc,

@subject = 'Important Customer Information Change',

@body = @body

This is the old code:


EXEC @retval = master.dbo.xp_sendmail


@recipients = @rec,

@blind_copy_recipients = @bcc,

@subject = 'Important Customer Information Change',

@message = @body

The problem now is that the application reports an update failure because the sp_send_dbmail return the message "Mail Queued."

I don't know if there's a way to suppress this message or not. Or some other way to indicate that "all is well" even though the stored procedure returned a message.

Thanks in advance.

View 6 Replies View Related

Sp_send_dbmail @query Results Truncated

Sep 21, 2007



Hi, sending a mail using sp_send_dbmail (as below) with attachment works. However the characters in the attacheted file gets truncated to 256. The file is populated with the results from the @query string.


EXECUTE msdb.dbo.sp_send_dbmail @profile_name = 'SQLAdmin'

,@recipients = 'a@a.com'

,@subject = 'Test'

,@body = 'Test'

,@body_format = 'TEXT'

,@query = 'SELECT distinct column FROM Table'

,@execute_query_database = 'PULSE'

,@attach_query_result_as_file = 1

,@query_result_header = 0

,@query_result_width = 32767

,@query_attachment_filename = 'a.pdf'

,@exclude_query_output = 1

,@query_no_truncate = 1

The value of MaxFileSize is 1 Mb when executing sysmail_help_configure_sp. It seems as if the @query_no_truncate value is being ignored by sp_send_dbmail procedure.

Any help would be appreciated.

View 2 Replies View Related

Sp_send_dbmail: Need Output To A Query Without The Messages.

Feb 27, 2008

I am writing a stored procedure which finally has to send mail to the customer with a list of phones that have been added to his account. I am getting these phones from a SQL Table in the form of a query, and including the output of the query(list of phones) , in the body of the mail.

There are two issues that I am unable to resolve,

1. I just want the output with no messages.



eg. 8887775567

not


8887777767 ( 1 row(s) effected)



2. One phone number per row.



8887775567
8009978776
6679800077

NOT


8887775567 8009978776 6679800077


Thanks in advance.




View 8 Replies View Related

Account Lockout Problem With Sp_send_dbmail

Sep 1, 2006

I am running this code in a job:

EXEC msdb.[dbo].sp_send_dbmail
@profile_name = 'Blah Blah',
@recipients = 'blah@blah.com',
@subject = 'Server Report 1',
@body = '',
@execute_query_database = 'DBInfo',
@query = 'EXEC dbo.usp_SvrRpt1;',
@query_result_header = 0,
@query_result_width = 300,
--@attach_query_result_as_file = 1,
@query_result_separator = '';
GO

Because I am creating a total of 6 server reports, I alter the subject and query like so:

@subject = 'Server Report X' --where X is replaced with values 1 to 6
@query = 'EXEC dbo.usp_SvrRptX' --where X is replaced with values 1 to 6

I can run 4 reports without any problems. If I run more than 4 reports in the same batch, my network account under Windows 2000 Activity Directory is locked out as if I had erroneously mistyped my password the number of time to meet the lockout requirement - in this case, the number is 3 login tries.

Is this a known problem with Database Mail? If so, is there a fix or workaround?

Thanks,

Neal

View 8 Replies View Related

Using Quotation Marks In A Msdb.dbo.sp_send_dbmail Query

Oct 31, 2007

Hi There,

I'm having a little trouble with a large query I have written to be sent as an email.

I want to send it as a csv so I've added commas in between each value in the query.

This is causing an error though, I think the ' that surround the commas are closing the query early. Is there any way around this? like encapsulating the query?

EXEC msdb.dbo.sp_send_dbmail
@profile_name = 'ggsgn'
,@recipients = 'sgsdm'

,@subject = 'Nsgdday'
,@attach_query_result_as_file = 1
,@body_format = 'text'
,@query ='
use sdgsgdgs
select
a1.c#,',', client,',', fr,',', tpe,',', dateReq as DateRequested,',', ... '

View 1 Replies View Related

Database Mail Sends Test Mails Successfully, But Sp_send_dbmail Fails

Apr 15, 2008



Hi all,

I am having a few problems with Database Mail and wondered if anyone could assist. It sends test mails fine, but when I run the following script:

(I've changed my email address in this post to test@test.com they are accurate in the scripts.)


EXEC msdb.dbo.sp_send_dbmail

@profile_name = 'Test Mail',

@recipients = 'test@test.com',

@body = 'Sent by sp_send_dbmail',

@Subject = 'SQL Server Email Test Email';


It gives the following errors.

(from the above script)


mailitem_id = 16
profile_id = 2
recipients = test@test.com
copy_recipients = NULL
blind_copy_recipients = NULL
subject = SQL Server Email Test Email
body = Sent by sp_send_dbmail
body_format = TEXT
importance = NORMAL
sensitivity = NORMAL
file_attachments = NULL
attachment_encoding = MIME
query = NULL
execute_query_database = NULL
attach_query_result_as_file = 0
query_result_header = 1
query_result_width = 256
query_result_separator =
exclude_query_output = 0
append_query_error = 0
send_request_date = 2008-04-15 10:50:03.827
send_request_user = COMPANYTest.Test
sent_account_id = NULL
sent_status = failed
sent_date = 2008-04-15 10:50:04.000
last_mod_date = 2008-04-15 10:50:04.513
last_mod_user = sa


(from the test mail)


mailitem_id = 11
profile_id = 2
recipients = test@test.com
copy_recipients = NULL
blind_copy_recipients = NULL
subject = Database Mail Test
body = This is a test e-mail sent from Database Mail on UKDEVSQL1
body_format = TEXT
importance = NORMAL
sensitivity = NORMAL
file_attachments = NULL
attachment_encoding = MIME
query = NULL
execute_query_database = NULL
attach_query_result_as_file = 0
query_result_header = 1
query_result_width = 256
query_result_separator =
exclude_query_output = 0
append_query_error = 0
send_request_date = 2008-04-15 09:51:46.530
send_request_user = COMPANYTest.Test
sent_account_id = 4
sent_status = sent
sent_date = 2008-04-15 09:51:46.000
last_mod_date = 2008-04-15 09:51:46.610
last_mod_user = sa


sysmail_event_log gives this error for mail item 16 (the scripted email):

The mail could not be sent to the recipients because of the mail server failure. (Sending Mail using Account 4 (2008-04-15T10:11:41). Exception Message: Cannot send mails to mail server. (Mailbox unavailable. The server response was: 5.7.1 Requested action not taken: message refused). )

View 2 Replies View Related

CLR-Based Trigger? Recursive Trigger? Common Table Expression?

Nov 14, 2006

Hey,

I'm new to this whole SQL Server 2005 thing as well as database design and I've read up on various ways I can integrate business constraints into my database. I'm not sure which way applies to me, but I could use a helping hand in the right direction.

A quick explanation of the various tables I'm dealing with:
WBS - the Work Breakdown Structure, for example: A - Widget 1, AA - Widget 1 Subsystem 1, and etc.
Impacts - the Risk or Opportunity impacts for the weights of a part/assembly. (See Assemblies have Impacts below)
Allocations - the review of the product in question, say Widget 1, in terms of various weight totals, including all parts. Example - September allocation, Initial Demo allocation, etc. Mostly used for weight history and trending
Parts - There are hundreds of Parts which will eventually lead to thousands. Each part has a WBS element. [Seems redundant, but parts are managed in-house, and WBS elements are cross-company and issued by the Government]
Parts have Allocations - For weight history and trending (see Allocations). Example, Nut 17 can have a September 1st allocation, a September 5th allocation, etc.
Assemblies - Parts are assemblies by themselves and can belong to multiple assemblies. Now, there can be multiple parts on a product, say, an unmanned ground vehicle (UGV), and so those parts can belong to a higher "assembly" [For example, there can be 3 Nut 17's (lower assembly) on Widget 1 Subsystem 2 (higher assembly) and 4 more on Widget 1 Subsystem 5, etc.]. What I'm concerned about is ensuring that the weight roll-ups are accurate for all of the assemblies.
Assemblies have Impacts - There is a risk and opportunity impact setup modeled into this design to allow for a risk or opportunity to be marked on a per-assembly level. That's all this table represents.

A part is allocated a weight and then assigned to an assembly. The Assemblies table holds this hierarchical information - the lower assembly and the higher one, both of which are Parts entries in the [Parts have Allocations] table.

Therefore, to ensure proper weight roll ups in the [Parts have Allocations] table on a per part-basis, I would like to check for any inserts, updates, deletes on both the [Parts have Allocations] table as well as the [Assemblies] table and then re-calculate the weight roll up for every assembly. Now, I'm not sure if this is a huge performance hog, but I do need to keep all the information as up-to-date and as accurate as possible. As such, I'm not sure which method is even correct, although it seems an AFTER DML trigger is in order (from what I've gathered thus far). Keep in mind, this trigger needs to go through and check every WBS or Part and then go through and check all of it's associated assemblies and then ensure the weights are correct by re-summing the weights listed.

If you need the design or create script (table layout), please let me know.

Thanks.

View 4 Replies View Related

Trouble With Update Trigger Modifying Table Which Fired Trigger

Jul 20, 2005

Are there any limitations or gotchas to updating the same table whichfired a trigger from within the trigger?Some example code below. Hmmm.... This example seems to be workingfine so it must be something with my specific schema/code. We'reworking on running a SQL trace but if anybody has any input, fireaway.Thanks!create table x(Id int,Account varchar(25),Info int)GOinsert into x values ( 1, 'Smith', 15);insert into x values ( 2, 'SmithX', 25);/* Update trigger tu_x for table x */create trigger tu_xon xfor updateasbegindeclare @TriggerRowCount intset @TriggerRowCount = @@ROWCOUNTif ( @TriggerRowCount = 0 )returnif ( @TriggerRowCount > 1 )beginraiserror( 'tu_x: @@ROWCOUNT[%d] Trigger does not handle @@ROWCOUNT[color=blue]> 1 !', 17, 127, @TriggerRowCount) with seterror, nowait[/color]returnendupdate xsetAccount = left( i.Account, 24) + 'X',Info = i.Infofrom deleted, inserted iwhere x.Account = left( deleted.Account, 24) + 'X'endupdate x set Account = 'Blair', Info = 999 where Account = 'Smith'

View 1 Replies View Related

Generic Audit Trigger CLR C#(Works When The Trigger Is Attached To Any Table)

Dec 5, 2006

This Audit Trigger is Generic (i.e. non-"Table Specific") attach it to any tabel and it should work. Be sure and create the 'Audit' table first though.

The following code write audit entries to a Table called
'Audit'
with columns
'ActionType' //varchar
'TableName' //varchar
'PK' //varchar
'FieldName' //varchar
'OldValue' //varchar
'NewValue' //varchar
'ChangeDateTime' //datetime
'ChangeBy' //varchar

using System;
using System.Data;
using System.Data.SqlClient;
using Microsoft.SqlServer.Server;

public partial class Triggers
{
//A Generic Trigger for Insert, Update and Delete Actions on any Table
[Microsoft.SqlServer.Server.SqlTrigger(Name = "AuditTrigger", Event = "FOR INSERT, UPDATE, DELETE")]

public static void AuditTrigger()
{
SqlTriggerContext tcontext = SqlContext.TriggerContext; //Trigger Context
string TName; //Where we store the Altered Table's Name
string User; //Where we will store the Database Username
DataRow iRow; //DataRow to hold the inserted values
DataRow dRow; //DataRow to how the deleted/overwritten values
DataRow aRow; //Audit DataRow to build our Audit entry with
string PKString; //Will temporarily store the Primary Key Column Names and Values here
using (SqlConnection conn = new SqlConnection("context connection=true"))//Our Connection
{
conn.Open();//Open the Connection
//Build the AuditAdapter and Mathcing Table
SqlDataAdapter AuditAdapter = new SqlDataAdapter("SELECT * FROM Audit WHERE 1=0", conn);
DataTable AuditTable = new DataTable();
AuditAdapter.FillSchema(AuditTable, SchemaType.Source);
SqlCommandBuilder AuditCommandBuilder = new SqlCommandBuilder(AuditAdapter);//Populates the Insert command for us
//Get the inserted values
SqlDataAdapter Loader = new SqlDataAdapter("SELECT * from INSERTED", conn);
DataTable inserted = new DataTable();
Loader.Fill(inserted);
//Get the deleted and/or overwritten values
Loader.SelectCommand.CommandText = "SELECT * from DELETED";
DataTable deleted = new DataTable();
Loader.Fill(deleted);
//Retrieve the Name of the Table that currently has a lock from the executing command(i.e. the one that caused this trigger to fire)
SqlCommand cmd = new SqlCommand("SELECT object_name(resource_associated_entity_id) FROM
ys.dm_tran_locks WHERE request_session_id = @@spid and resource_type = 'OBJECT'", conn);
TName = cmd.ExecuteScalar().ToString();
//Retrieve the UserName of the current Database User
SqlCommand curUserCommand = new SqlCommand("SELECT system_user", conn);
User = curUserCommand.ExecuteScalar().ToString();
//Adapted the following command from a T-SQL audit trigger by Nigel Rivett
//http://www.nigelrivett.net/AuditTrailTrigger.html
SqlDataAdapter PKTableAdapter = new SqlDataAdapter(@"SELECT c.COLUMN_NAME
from INFORMATION_SCHEMA.TABLE_CONSTRAINTS pk ,
INFORMATION_SCHEMA.KEY_COLUMN_USAGE c
where pk.TABLE_NAME = '" + TName + @"'
and CONSTRAINT_TYPE = 'PRIMARY KEY'
and c.TABLE_NAME = pk.TABLE_NAME
and c.CONSTRAINT_NAME = pk.CONSTRAINT_NAME", conn);
DataTable PKTable = new DataTable();
PKTableAdapter.Fill(PKTable);

switch (tcontext.TriggerAction)//Switch on the Action occuring on the Table
{
case TriggerAction.Update:
iRow = inserted.Rows[0];//Get the inserted values in row form
dRow = deleted.Rows[0];//Get the overwritten values in row form
PKString = PKStringBuilder(PKTable, iRow);//the the Primary Keys and There values as a string
foreach (DataColumn column in inserted.Columns)//Walk through all possible Table Columns
{
if (!iRow[column.Ordinal].Equals(dRow[column.Ordinal]))//If value changed
{
//Build an Audit Entry
aRow = AuditTable.NewRow();
aRow["ActionType"] = "U";//U for Update
aRow["TableName"] = TName;
aRow["PK"] = PKString;
aRow["FieldName"] = column.ColumnName;
aRow["OldValue"] = dRow[column.Ordinal].ToString();
aRow["NewValue"] = iRow[column.Ordinal].ToString();
aRow["ChangeDateTime"] = DateTime.Now.ToString();
aRow["ChangedBy"] = User;
AuditTable.Rows.InsertAt(aRow, 0);//Insert the entry
}
}
break;
case TriggerAction.Insert:
iRow = inserted.Rows[0];
PKString = PKStringBuilder(PKTable, iRow);
foreach (DataColumn column in inserted.Columns)
{
//Build an Audit Entry
aRow = AuditTable.NewRow();
aRow["ActionType"] = "I";//I for Insert
aRow["TableName"] = TName;
aRow["PK"] = PKString;
aRow["FieldName"] = column.ColumnName;
aRow["OldValue"] = null;
aRow["NewValue"] = iRow[column.Ordinal].ToString();
aRow["ChangeDateTime"] = DateTime.Now.ToString();
aRow["ChangedBy"] = User;
AuditTable.Rows.InsertAt(aRow, 0);//Insert the Entry
}
break;
case TriggerAction.Delete:
dRow = deleted.Rows[0];
PKString = PKStringBuilder(PKTable, dRow);
foreach (DataColumn column in inserted.Columns)
{
//Build and Audit Entry
aRow = AuditTable.NewRow();
aRow["ActionType"] = "D";//D for Delete
aRow["TableName"] = TName;
aRow["PK"] = PKString;
aRow["FieldName"] = column.ColumnName;
aRow["OldValue"] = dRow[column.Ordinal].ToString();
aRow["NewValue"] = null;
aRow["ChangeDateTime"] = DateTime.Now.ToString();
aRow["ChangedBy"] = User;
AuditTable.Rows.InsertAt(aRow, 0);//Insert the Entry
}
break;
default:
//Do Nothing
break;
}
AuditAdapter.Update(AuditTable);//Write all Audit Entries back to AuditTable
conn.Close(); //Close the Connection
}
}


//Helper function that takes a Table of the Primary Key Column Names and the modified rows Values
//and builds a string of the form "<PKColumn1Name=Value1>,PKColumn2Name=Value2>,......"
public static string PKStringBuilder(DataTable primaryKeysTable, DataRow valuesDataRow)
{
string temp = String.Empty;
foreach (DataRow kColumn in primaryKeysTable.Rows)//for all Primary Keys of the Table that is being changed
{
temp = String.Concat(temp, String.Concat("<", kColumn[0].ToString(), "=", valuesDataRow[kColumn[0].ToString)].ToString(), ">,"));
}
return temp;
}
}

The trick was getting the Table Name and the Primary Key Columns.
I hope this code is found useful.

Comments and Suggestion will be much appreciated.

View 16 Replies View Related

Trigger - Require Help For Updating A Trigger Following An INSERT On Another Table

Oct 30, 2007

Table 1





First_Name

Middle_Name

Surname


John

Ian

Lennon


Mike

Buffalo

Tyson


Tom

Finney

Jones

Table 2




ID

F

M

S

DOB


1

Athony

Harold

Wilson

24/4/67


2

Margaret

Betty

Thathcer

1/1/1808


3

John

Ian

Lennon

2/2/1979


4

Mike

Buffalo

Tyson

3/4/04


5

Tom

Finney

Jones

1/1/2000


I want to be able to create a trigger that updates table 2 when a row is inserted into table 1. However I€™m not sure how to increment the ID in table 2 or to update only the row that has been inserted.

View 17 Replies View Related







Copyrights 2005-15 www.BigResource.com, All rights reserved