Trigger :: Xp_smtp_sendmail :: Parameter Value In Message/subject :: Magic Table

Oct 23, 2007

OK so now I'm setting up a trigger to email info to different people based on values INSERTed into one of my tables. I'm using an IF statement to determine who I'm giong to send the mail to, but I don't really understand how to include the data (parameters) in my message. Thanks for any help. Here's what I have so far.





Code Block
ALTER TRIGGER [smallin].[trig_test]
ON [smallin].[DATALIST]
AFTER INSERT
AS
declare @rc int,
@post bit,
@pre bit
SELECT @post = [POST], @pre = [PRE] FROM inserted
IF @post = 1
exec @rc = master.dbo.xp_smtp_sendmail
@FROM = N'ln.li@mydomain.com',
@FROM_NAME = N'Alert Mailer',
@TO = N's.mallin@mydomain.com',
@replyto = N'ln.li@mydomain.com',
@CC = N'',
@BCC = N'',
@priority = N'NORMAL',
@subject = N'This is post data',
@message = N'Goodbye MAPI and Outlook',
@messagefile = N'',
@type = N'text/plain',
@attachment = N'',
@attachments = N'',
@codepage = 0,
@server = N'exchange.mydomain.com'

ELSE IF @pre = 1
exec @rc = master.dbo.xp_smtp_sendmail
@FROM = N'ln.li@mydomain.com',
@FROM_NAME = N'Alert Mailer',
@TO = N's.mallin@mydomain.com',
@replyto = N'ln.li@mydomain.com',
@CC = N'',
@BCC = N'',
@priority = N'NORMAL',
@subject = N'This is pre data',
@message = N'Goodbye MAPI and Outlook',
@messagefile = N'',
@type = N'text/plain',
@attachment = N'',
@attachments = N'',
@codepage = 0,
@server = N'exchange.mydomain.com'





View 5 Replies


ADVERTISEMENT

What Is Magic Table?

Jan 1, 2004

Hi,
I want to know about magic table in SQL Server. What is actually magic table?
I tried to find information through google but I didnt able to get sufficient information about it. Can any budy help me in this regard?

Thanx.

View 3 Replies View Related

Subject: How To Join A Table With Other (result) Tables ? Complex !

Aug 25, 2005

Here is the situation

Table 1 : tbl_documents

docIDdocName
1aaa
2bbb
3ccc

Table 2 : tbl_Rating

ratIDratingdocID
131
251
321
432

The queary I need is to display the result in this form. must be like this

docIDdocName Avaragerating
1aaa3
2bbb3
3ccc0

NOTE : For getting the average I used this queary “SELECT SUM(rating) As
RatingSum, COUNT(*) As RatingCount FROM tbl_Rating WHERE tbl_rating.docID =
tbl_documents.docID”

PLs help me ?

Thx

View 3 Replies View Related

Table Design Question - Subject Matter Expert Database

Aug 8, 2007

I would like to create a database that keeps track of our companies subject matter experts. I have roughed out some of the tables. I would appreciate any feedback on if this is the right approach and if there might be any issues when I start writting a front-end (probably VB 2005).

What makes this interesting (at least for me) is that a subject has an owner and at least 1 "expert", possibly up to 3. Here is what I am thinking for tables:

tblEmployee

EmployeeID (PK)
LastName
FirstName
etc......
tblSubject

SubjectID (PK)
Description
tblOwner

SubjectID (FK)
EmployeeID (FK)
tblExpert1

SubjectID (FK)
EmployeeID (FK)
tblExpert2

SubjectID (FK)
EmployeeID (FK)
tblExpert3

SubjectID (FK)
EmployeeID (FK)



Does this make sense? Would I run into any issues when trying to display this on a form in VB?

Thanks in advance for any help!!!!!

Cal

View 8 Replies View Related

T-SQL (SS2K8) :: Retrieve Subject Wise Highest Marks List In A Table?

Jul 18, 2011

I have a requirement like, we are having two tables in our database.

Table names: student, marklist

Student table values:

id studname
------------------
1x
2y
3z
4a
5b

Marklist table values:

id maths physics English
---------------------------------
1506070
2706040
3508070
45010070
5906070

But my requirement is, I need to display the data "subject wise" highest marks for each student.

for example:

id name highestmark
---------------------------------
1 x English

View 9 Replies View Related

Service Broker: Trigger On New Message

Jul 13, 2007

Hi,



I have a small problem with my two databases ( A and B ).



On database A I have a queue set up for receiving messages from a service broker which are sent via a stored procedure from database B ...



Each time a message hits the queue on database A I would like to run a stored procedure that takes the message and actions it.





I have my stored procedures in place but can't figure out how to trigger a procedure each time a message is received. I have read this ( http://technet.microsoft.com/en-us/library/ms171601.aspx ) but would really appreciate someone posting an example of setting up queue activation.



Many thanks



Chris

View 1 Replies View Related

Trigger Doesn't Log Into The Audit Table If The Column Of Table Has Trigger On Is Null

Jan 23, 2008



Hi,

I have a trigger set on TABLE1 so that any update to this column should set off trigger to write to the AUDIT log table, it works fine otherwise but not the very first time when table1 has null in the column. if i comment out

and i.req_fname <> d.req_fname from the where clause then it works fine the first time too. Seems like null value of the column is messing things up

Any thoughts?


Here is my t-sql


Insert into dbo.AUDIT (audit_req, audit_new_value, audit_field, audit_user)

select i.req_guid, i.req_fname, 'req_fname', IsNull(i.req_last_update_user,@default_user) as username from inserted i, deleted d

where i.req_guid = d.req_guid

and i.req_fname <> d.req_fname



Thanks,
leo

View 7 Replies View Related

Can't Receive Message From Queue (Async Trigger)

Sep 1, 2006

Hi Folks,

I've found a pretty good code example on http://www.dotnetfun.com for a Asynchronous Trigger.

I've parsed through the Code, to understand how to wirte my own Async Trigger with a Service Broker, but the Code isn't working! It seems that the stored procedure don't receive the messages in the queue, but the queue get's filled.

MessageType


 CREATE MESSAGE TYPE  myMsgXML
 VALIDATION = WELL_FORMED_XML;
Contract

CREATE CONTRACT myContractANY
 (myMsgXML SENT BY ANY)
Queue

CREATE QUEUE myQueue
 WITH STATUS = ON,
 RETENTION = ON,
 ACTIVATION
 (
  STATUS = ON,
  PROCEDURE_NAME = sp_myServiceProgram,
  MAX_QUEUE_READERS = 5,
  EXECUTE AS SELF
 )
Service

CREATE SERVICE myService ON QUEUE myQueue  (myContractANY)
Procedure (greped from http://www.dotnetfun.com/)

CREATE PROC sp_myServiceProgram
AS
-- This procedure will get triggered automatically
-- when a message arrives at the
-- Let's retrieve any messages sent to us here:
DECLARE @XML XML,
  @MessageBody VARBINARY(MAX),
  @MessageTypeName SYSNAME,
  @ID INT,
  @COL2 VARCHAR(MAX);
DECLARE @Queue TABLE (
  MessageBody VARBINARY(MAX),
  MessageTypeName SYSNAME);
WHILE (1 = 1)
BEGIN
 WAITFOR (
  RECEIVE message_body, message_type_name
  FROM myQueue  INTO @Queue
 ), TIMEOUT 5000;
 -- If no messages exist, then break out of the loop:
 IF NOT EXISTS(SELECT * FROM @Queue) BREAK;
 DECLARE c_Test CURSOR FAST_FORWARD
  FOR SELECT * FROM @Queue;
 OPEN c_Test;
 FETCH NEXT FROM c_Test
  INTO @MessageBody, @MessageTypeName;
 WHILE @@FETCH_STATUS = 0
 BEGIN
  -- Let's only deal with messages of Message Type
  -- myMsgXML:
  IF @MessageTypeName = 'myMsgXML'
  BEGIN
   SET @XML = CAST(@MessageBody AS XML);
   -- Now let's save the XML records into the
   -- historical table:
   INSERT INTO tblDotNetFunTriggerTestHistory
    SELECT tbl.rows.value('@ID', 'INT') AS ID,
     tbl.rows.value('@COL2', 'VARCHAR(MAX)') AS COL2,
     GETDATE() AS UPDATED
    FROM @XML.nodes('/inserted') tbl(rows);
  END
  FETCH NEXT FROM c_Test
   INTO @MessageBody, @MessageTypeName;
 END
 CLOSE c_Test;
 DEALLOCATE c_Test;
 -- Purge the temporary in-proc table:
 DELETE FROM @Queue;
END
Send Message in a Update Trigger

SELECT @XML = (SELECT * FROM inserted FOR XML AUTO);
  -- Send the XML records to the Service Broker queue:
  DECLARE @DialogHandle UNIQUEIDENTIFIER,
   @ConversationID UNIQUEIDENTIFIER;
  /*
   The target Service Broker service is the same
   service as the initiating service; however, you
   can set up this type of trigger to send messages
   to a remote server or another database.
  */
  BEGIN DIALOG CONVERSATION @DialogHandle
   FROM SERVICE myService
   TO SERVICE 'myService'
   ON CONTRACT myContractANY;
  SEND ON CONVERSATION @DialogHandle
   MESSAGE TYPE myMsgXML
   (@XML);
  -- Let's detect an error state for this dialog
  -- and rollback the entire transaction if one is
  -- detected:
  IF EXISTS(SELECT * FROM sys.conversation_endpoints
   WHERE conversation_handle = @DialogHandle
   AND state = 'ER')
   RAISERROR('Dialog in error state.', 18, 127);
  ELSE
  BEGIN
   --I want to list the queue after the trigger so I disabled
   --END CONVERSATION @DialogHandle;
   COMMIT TRAN;
  END
The Problem is, that the Procedure doesn't even get started! So I tried to receive the Queues manually

WAITFOR (
  RECEIVE message_body, message_type_name
  FROM myQueue  INTO @Queue
 ), TIMEOUT 5000;

and I run always into the timeout and get nothing back. A Select * FROM myQueue gives me some results back. Why I can't recevie?
Would be grateful for help, or at least a good tutorial, I haven't found one yet....
thx and greez
     Karsten

View 1 Replies View Related

Looking For Some Magic

May 16, 2006

... well, perhaps some sophistication. The setup:

Server A publishes to server B via transactional replication. Server A is to be shut down while some electrical work is done. So we fail over to server B for a couple days. My underpowered brain says to shut down replication, possibly fail over well in advance of the power outage.

Then, when the electrical work is done and server A is restarted: 1) stop work on server B, 2) ?copy? the database on B to A (I suppose after deleting it from A), and 3) redoing the replication from scratch.

Can anyone recommend a better process?

I am very gratefull for any enlightenment.

View 1 Replies View Related

Xp_smtp_sendmail

Aug 2, 2006

Any idea when this extended stored procedure gets installed in SQL 2000 as I get just the error message below when I try to run it:

Could not find stored procedure 'master.dbo.xp_smtp_sendmail'.

View 3 Replies View Related

Xp_smtp_sendmail With 64-bit Version? (was DBA)

Aug 3, 2006

does anyone knows if there is such xp_smtp_sendmail with 64-bit version?

View 1 Replies View Related

Xp_smtp_sendmail/xpsmtp80.dll

Sep 8, 2006

Hi!

I am using SQL Server 2000. I wanted to send MIME type mail through SQL Mail. So I downloaded xpsmtp80.dll and copied to C:Program FilesMicrosoft SQL ServerMSSQLBinnDLL. Then I registered it by exec sp_addextendedproc 'xp_smtp_sendmail', 'xpsmtp80.dll'. I granted permission to public by grant execute on xp_smtp_sendmail to public.Now when I am executing this

declare @rc int
exec @rc = master.dbo.xp_smtp_sendmail
@FROM = N'MyEmail@MyDomain.com',
@TO = N'MyFriend@HisDomain.com',
@subject = N'My first HTML mail',
@message = N'<HTML><H1>This is some HTML content</H1></HTML>',

@type = N'text/html'
select RC = @rc
go



An error generating stating

ODBC: Msg 0, Level 16, State 1

Cannot load the DLL xpsmtp80.dll, or one of the DLLs it references. Reason: 126(The specified module could not be found.).



(1 row(s) affected)



Please anyone help me to sort out this problem.

View 1 Replies View Related

What Are Magic Tables?

Feb 23, 2004

Can any one tell me what are magic tables in sql server?

View 6 Replies View Related

Problems Using Xp_smtp_sendmail

Jul 20, 2005

I am trying to use this code to send an emaildeclare @rc int,@invjournal intset @invjournal = 2222exec @rc = master.dbo.xp_smtp_sendmail@FROM= N'matt@hasta.se',@FROM_NAME= N'Matt Douhan',@TO= N'inventering@hasta.se',@replyto = N'Reply to NONE',@CC= N'',@BCC= N'',@priority= N'NORMAL',@subject= N' TEST TEST TEST Inventeringsjournal '+@invjournal+'klar för integration till redovisningen TEST TEST TEST',@message= N'Vänligen uppdatera denna inventeringsjournal tillredovisningen',@messagefile= N'',@type= N'text/plain',@attachment= N'',@attachments= N'',@codepage= 0,@server = N'mandarin.internal.hasta.se'select RC = @rcgobut it fails with the following with the following error msgServer: Msg 170, Level 15, State 1, Line 14Line 14: Incorrect syntax near '+'.the problem seems to be when I want to use the @invjournal variable inthe subject, if I take it away and only send text it works just fine.Any ideas would be much appreciatedrgdsMatt

View 1 Replies View Related

Permissions For Xp_smtp_sendmail?

Apr 14, 2008



(Apologies if this is in the wrong section.)

I'm been using xp_smtp_sendmail in SQL2000 for firing off task assignment emails from a ASP.NET website which uses Integrated security to connect.

Everything has been fine in the past but now these EMail have stopped being sent. (Can't give an accurate date as to when)

The same thing is now happening on my local machine as well, everything appears to run fine - xp_smtp_sendmail does not send back an error code it's just that the EMail is not sent. The unusual thing is that if I run the exact same code (lifted from Profiler) in SQL Analyser then the mail is fired off no problem.

Things I have tried...
Set Chaining in Calling DB.
Set Website conn string from integrated to use sa login.
Opened up permissions for ASPNET user.
Created sproc in master to do call to xp.
Reloaded xp_smtp_sendmail and set permissions.

I'm now at a dead end and would be grateful for any helpideas.

View 2 Replies View Related

Publishing Wizard - Bad Magic?

Aug 26, 2007

I've been working with the Database Publishing Wizard and have found what I initially thought was a bug but have decided is a rather nasty "feature".  Or am I missing something?
I have membership implemented in a live database. I took a backup and loaded it into a local database. I created a new table locally that is foreign-keyed off aspnet_roles, and added some data.
Using the Publishing Wizard for a partial deployment, I followed the steps which seem perfectly clear to script out ONLY the new table and its data. The screens provide a nice GUI for selecting specific database objects, and I carefully chose the one new table.
From good habits I looked at the script before deploying it. It drops and recreates aspnet_roles and aspnet_applications as well (and inserts the data from the development tables).
Presumably this is because of the foreign key relationships. But there's no need to do so. What if I or another developer had added in some roles to the live table in the meantime? This script would blow them away.
Am I missing an option with the Wizard that would script out only what is specified? I've tidied up the script (i.e. removed the undesirable sections) - but this seems to be a naughty wizard. Any thoughts?

View 5 Replies View Related

The SMTP Server In Xp_smtp_sendmail

Sep 23, 2005

Just trying out xp_smtp_sendmail for the first time.I get the error:Error: connecting to server smarthostOK, so I don't have the server parameter for SMTP server set upcorrectly.I don't even know what an SMTP Server is! Is this an e-mail providerthat provides SMTP functionality, or an application I need to install?

View 4 Replies View Related

What's Magic About DT_STR And Size 50

May 15, 2006

Okay, this is probably my own stupidity but here goes. I am trying to make a very rudimentary package. I've got a data flow that has a flat file source. This source has fields delimited by the | symbol. I give the fields in the flat file source names. The first field is always exactly 1 character. When I use the advanced editor to look at the fields' properties, I see the first field, called ProductLine, is considered to be of SSIS internal data type DT_STR with a length of 50. I change the 50 to 1 because that is as long as that field is.

No matter what I do, when I close the advanced editor and then open it again, the field length for ProductLine is again set to 50. The field is 1 long, not 50 long. How can I make the setting of 1 be retained? Nothing I do changes it. What is the point of allowing the length to be editable if the edit is not retained?

Thanks in advance,



SW

View 4 Replies View Related

What Are The Magic Tables In Sql Server ?

Mar 11, 2008



Hello what does it mean ? Is it really posible in SQL Server ? If yes then How ?

View 7 Replies View Related

SQL Server 2012 :: Concat Parameter In A Message

Jun 2, 2014

I have a procedure (a) where i call another procedure (b) passing @message as a parameter to procedure B.

Ex:
Create procedure a
as
Begin
declare @prevyear
exec b @message = 'avvasdva' + cast(@prevyear as varchar)
End

When i execute above procedure, i get error at + sign i.e. @message parameter. how can i concatenate string with another parameter when passing parameters

View 3 Replies View Related

Error Message In Set Datefirst 7 And Report Parameter

Nov 27, 2007



Hi,

I am setting my Dataset in SSRS to define the First Day of the week to Sunday.
So In the Dataset I put this scripting :
==================================
SET DATEFIRST 7;
SELECT city, country, datepart(wk,transactdate) as WeekNo from CatalogTable
==================================
The select statement above working very fine in the report.

But then, when I put in the Parameter which I have set in Report Parameter for a field called Service then I will get the problem.
For example the scripting below : ==================================
SET DATEFIRST 7;
SELECT city, country, datepart(wk,transactdate) as WeekNo from CatalogTable
where Service IN (@PService)
==================================
I have defined @PService in Report Parameter, and in the Parameter Tab in Dataset inside SSRS.
But it kept prompting me with the eror message :
Error Source : .Net SqlClient Data Provider
Error Message : Must declare the scalar variable "@PService".

When I remove the first line SET DATEFIRST 7; then my query working fine.

It seems SSRS cannot accept SET statement, whenever we insert the parameter in there.
Is there any workaround on this ?

Appreciate a lot for your help.

cheers,
Tanipar




View 1 Replies View Related

Transact SQL :: How To Set Error Message To Output Parameter

Aug 31, 2015

In Sql Server 2008 R2, I am creating a procedure with multiple transactions in it. Try..Catch Block is used for each transaction. I use output parameter to catch the error code and message since it will be caught by the main program. But When there is errors the output parameter are not correct set to the error message and code?

create procedure xxx (@P_Return_Status VARCHAR(1) OUTPUT, @P_Error_Code INT OUTPUT,)
AS
BEGIN
BEGIN TRY
BEGIN TRANSACTION TR1
.....
COMMIT TRANSACTIOn TR1
END TRY

[code].....

View 4 Replies View Related

CLR Trigger -&&> Send Insert/Update/Delete Message To Windows Service

Feb 1, 2007

Hi,

I have an c# windows service, which is running on the same machine where my mssql server is installed. This service must be informed for each insert/update/delete event on one specific table.

My idea was to create an CLR Trigger for this table which can communicate with this service via .NET remoting. But the problem is, that the system.runtime.remoting assembly is not integrated within the mssql clr enviroment => i can't use remoting.

Are there any other idea's how can i solve this?

Best regards,
Thomas

View 2 Replies View Related

Magic Tables With Text Columns

Oct 6, 2004

Hi folks,

I need to execute some kind of

select a,b,c into #inserted from inserted

a = int
b = varchar(50)
c = text

Easy so far. But I what I need is to find out whether the audited table contains text(or nText / image) columns or not. If it contains any text columns the statement should automatically be changed to

select a,b into #inserted from inserted

Remember that the trigger must be usable for any table in the database without manually entering the tables structure or the column names.

Best would be fetching the structure fropm the system views (INFORMATIONSCHEMES)

Any suggestions ?

Thanks a lot!

Stefan

View 1 Replies View Related

Xp_smtp_sendmail Not Sending HTML File Right

Sep 27, 2007

Hello All.

I sent a HTML file as text message using xp_smtp_sendmail from my SQL server but the test email that I received doesn't look like the HTML file I have originally. Below are my codes:-

exec @rc = master.dbo.xp_smtp_sendmail
@FROM = N'xxx@yyy.com',
@FROM_NAME = N'Mr XXX',
@TO = N'www@yyy.com',
@CC = N'kkk@yyy.com',
@priority = N'HIGH',
@subject = N'Weekly Sales To Thirds',
@type = N'text/html',
@messagefile = N'D:WSTWeeklySalesToThirds.htm',
@server = N'999.99.999.99',
@attachments = N'D:WST4weeksWST.xls'
select RC = @rc


The problem I have is the email doesn't display the HTML correctly. Spaces appeared and some of wording have wrapped.

I have attached partial screen shots of my original HTML file and email.

Please help if you have similar problem and solution. Thank you.

Best regards
Teck Boon

View 2 Replies View Related

Xp_smtp_sendmail Html+plain Text

Jul 20, 2005

Hi all. Iv'e tryed out xp_smtp_sendmail, and I like what I can see sofar. The thing I wonder about is if the xp supports sending both htmlAND plain text in the same mail. I'm on a sql2000 sp3 and I have noproblem with the xp when i either send plain text or html, but asstated above I need to send with both formats in one mail......For use when one does not know if the receiver uses a mail-client thatsupports html or not. If not does anyone know of a good way to attackthis problem?thanks in advanceKarl B

View 1 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

SQL Server 2012 :: SSRS - Display A Message When User Enter Wrong Parameter?

Mar 12, 2015

Issue #1 I have a report that takes 8 character parameter, A error message needs to popped out if user enters parameter less than 8 character.

Issue #2 I have a report with Tablix. A message needs to display if Tablix returns no Rows.

View 1 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

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

Feb 5, 2008

A





ID

Name


1

Joe


2

Fred


3

Ian


4

Bill


B





ID


1


4

I want to be able to create a trigger so that when a row is inserted into table A by a specific user then the ID will appear in table B. Is it possible to find out the login id of the user inserting a row?

I believe the trigger should look something like this:

create trigger test_trigger
on a
for insert
as
insert into b(ID)

select i.id
from inserted i
where
--specific USER

View 9 Replies View Related

Pass A Parameter To A Trigger

Sep 15, 2005

Hello,
 
Is there a way to pass a parameter to a trigger?
Thanks,

View 1 Replies View Related







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