Using Trigger To Notify An Assembly Of Changes.

Oct 13, 2006

I have a requirement to create a sorted list of objects, stored within
an assembly, and I would like to use a After Insert/Update trigger to
notify that assembly that something has changed, rather than polling
the database for changes all the time.

My initial problem is that I need to create a static list so that it
can be dynamically looked at by other assemblies, but SQL Server won't
allow me to attach a dll which contains a static method.

Has anyone done something like this? Are there any decent examples
available anywhere?

any help will be appreciated.

simo

View 4 Replies


ADVERTISEMENT

Notify Whether A Trigger Is Triggered...?

Aug 27, 2007

Hi,
I am developing desktop application with SQL Server 2005 in C#. I need your help. My Question is "How to notify a Database trigger is executed thru C# application?".
Now I am going to explain clearly. I have a table "Employee" and I created one trigger (it may be INSERT/UPDATE/DELETE) for that table. Then I created a C# application to show a msg box when that table is modified. Now my question is If that table is modified a message box will be shown. I know about trigger (If trigger assigned table is modified that trigger will automatically executed.) But how do i know that trigger is executed thru a C# application. Please send your suggestion or links.

Thanx,

GANESAN MURUGESAN.

View 9 Replies View Related

SQL Trigger To Notify VB.NET Application ?

Aug 10, 2007

Hi all,

I have a VB.NET 2005 application that needs to monitor constantly each change of a field on a SQL server 2005.
Is there a way of setting a trigger up in the SQL Server that notifies the VB.NET application to avoid having the VB.NET apllication querying the SQL table all day for changes?

The table in SQL stores a temperature value. I need the VB.NET application to receive this value everytime there's a change. I could do a timer on the VB.NET application to check for changes in the table every 1 second but I don't think this is efficient. The temperature value may change once every two or three seconds.

The VB.NET application will process the temperature value.

Is there a way of notifying the VB.NET application (which runs from a different server) from within SQL Server? If so, how? If not, what would you go about implementing this?

Thanks again for your comments,

ST

View 1 Replies View Related

Can't Drop Trigger Assembly

Jun 20, 2006

Created an assembly based on this article...

http://sqljunkies.com/Article/4CD01686-5178-490C-A90A-5AEEF5E35915.scuk

Now I want to make changes and redeploy the assembly but when I try to drop I get this.

IF EXISTS (SELECT * FROM sys.assemblies asms WHERE asms.name = N'AuditCommon')

DROP ASSEMBLY [AuditCommon]

Msg 6590, Level 16, State 1, Line 3

DROP ASSEMBLY failed because 'AuditCommon' is referenced by object 'clr_trigger'.

Any ideas?

View 3 Replies View Related

ALTER ASSEMBLY Error Msg 6509 An Error Occurred While Gathering Metadata From Assembly ‘&&<Assembly Name&&>’ With HRESULT 0x1.

Feb 22, 2008

I work with February CTP of SqlServer 2008.
I have an Assembly with several UDTs inside. Version of assembly is 1.0.*
I use CREATE ASSEMBLY statement to register this assembly, and it runs without any errors. Then I rebuild CLR solution without doing any changes in source code. In that case the only difference between new and old assemblies is version (difference in fourth part of version).
Then I try to update assembly in SqlServer. I use
ALTER ASSEMBLY <name>
FROM <path>
WITH PERMISSION_SET = UNSAFE, UNCHECKED DATA
statement for this. Statement runs with error:
Msg 6509An error occurred while gathering metadata from assembly €˜<Assembly name>€™ with HRESULT 0x1.
I found the list of condition for ALTER ASSEMBLY in MSDN:
ALTER ASSEMBLY statement cannot be used to change the following:
· The signatures of CLR functions, aggregate functions, stored procedures, and triggers in an instance of SQL Server that reference the assembly. ALTER ASSEMBLY fails when SQL Server cannot rebind .NET Framework database objects in SQL Server with the new version of the assembly.
· The signatures of methods in the assembly that are called from other assemblies.
· The list of assemblies that depend on the assembly, as referenced in the DependentList property of the assembly.
· The indexability of a method, unless there are no indexes or persisted computed columns depending on that method, either directly or indirectly.
· The FillRow method name attribute for CLR table-valued functions.
· The Accumulate and Terminate method signature for user-defined aggregates.
· System assemblies.
· Assembly ownership. Use ALTER AUTHORIZATION (Transact-SQL) instead.
Additionally, for assemblies that implement user-defined types, ALTER ASSEMBLY can be used for making only the following changes:
· Modifying public methods of the user-defined type class, as long as signatures or attributes are not changed.
· Adding new public methods.
· Modifying private methods in any way.

But I haven€™t done any changes in source code, so new version of assembly satisfies all this conditions.
What could be the reason for such behavior?
P.S. I€™ve got the same error, if I add or change any method in assembly before rebuilding.

View 9 Replies View Related

Msg 6573 Method, Property Or Field In Assembly Is Not Static. VB.Net Assembly In SQL Server Problem

Feb 29, 2008



I am trying to get a function I created in VB 5 for Access and Excel to work in SQL 2005. I was able to update the old VB code to work in VB 2005. I compiled and made a .dll, and I was able to register the new Assembly in SQL Server. When I try to create the Function, I get an error:


CREATE FUNCTION dbo.Temperature(@FluidName char, @InpCode Char, @Units Char, @Prop1 varchar, @Prop2 varChar)

RETURNS VarChar

AS EXTERNAL NAME FluidProps.[FluidProps.FluidProperties.Fluids].Temperature


Error returned:


Msg 6573, Level 16, State 1, Procedure Temperature, Line 21

Method, property or field 'Temperature' of class 'FluidProps.FluidProperties.Fluids' in assembly 'FluidProps' is not static.



Here is the code (part of it) in the VB class:

Header:


Imports Microsoft.SqlServer.Server

Imports System.Data.SqlClient

Imports System.Runtime.InteropServices

Imports System.Security

Imports System.Security.Permissions





Namespace FluidProperties



'Option Strict Off

'Option Explicit On

Public Partial Class Fluids

Function:


Function Temperature(ByRef FluidName As Object, ByRef InpCode As Object, ByRef Units As Object, ByRef Prop1 As Object, Optional ByRef Prop2 As Object = Nothing) As Object

Call CalcProp(FluidName, InpCode, Units, Prop1, Prop2)

Temperature = ConvertUnits("-T", Units, T, 0)

End Function


If I change the Function Temperature to Static, I get an error that functions cannot be Static. Its been a long time since I created the code and am having a hard time in my older age of getting the cobwebs out to make it work.

I have no problem getting the function to work if I call it from a VB form....so what do I need to do to get it to work on data in my SQL server?

Thanks

Buck

View 20 Replies View Related

Failed To Load Expression Host Assembly. Details: StrongName Cannot Have An Empty String For The Assembly Name.

Jan 12, 2006

I previously had an ASP.NET 1.1 site running on my IIS 6.0 server (not the default website) with Reporting Services running in a subdirectory of that website.  I recently upgraded to ASP.NET 2.0 for my website and was greeted with an error when trying to view a report.  The error was very non-descript, but when I checked the server logs, it recorded the details as "It is not possible to run two different versions of ASP.NET in the same IIS process.  Please use the IIS Administration Tool to reconfigure your server to run the application in a separate process."

 

First of all, I could not figure out where and how to do this.  Secondly, I decided to try to also change the Reporting Services folders to run ASP.NET 2.0 and when I did, I was greeted with the following message when attempting to view a report:

 

"Failed to load expression host assembly. Details: StrongName cannot have an empty string for the assembly name."

Please help.

View 7 Replies View Related

Creating A System.Management Assembly In Order For My Own Assembly To Work?

Aug 2, 2006

Hi

I am a bit paranoid about what I just did to my SQL Server 2005 with this CLR experiment.

I created a Class Lib in C# called inLineLib that has a class Queue which represents an object with an ID field.

in another separate namespace called inLineCLRsql, I created a class called test which will hold the function to be accessed from DB, I referenced and created an instances of the Queue class, and retrieve it's ID in a function called PrintMessage.

namespace inlineCLRsql{


public static class test{


public static void PrintMessage(){



inLineLib.Queue q = new inLineLib.Queue();

int i = q.queueId ;

Microsoft.SqlServer.Server.SqlContext.Pipe.Send(i.ToString());



}

}

}

to access this from the db, I attempted to create an assembley referencing inLineCLRsql.dll. This didn't work as it complained about inLineLib assembly not existing in the db. I then attempted to create an assembley for inLineLib but it barfed saying System.Management assembly not created.

so what I did is (and this is where I need to know if I just ruined sql server or not):

1- ALTER DATABASE myDB SET TRUSTWORTHY ON;.

2- CREATE ASSEMBLY SystemManagement

FROM 'C:WINDOWSMicrosoft.NETFrameworkv2.0.50727System.Management.dll'

WITH PERMISSION_SET = UNSAFE

3- CREATE ASSEMBLY inLineLibMaster

FROM 'D:inLineServerinLineLibinDebuginLineLib.dll'

WITH PERMISSION_SET = unsafe

4- and finally

CREATE ASSEMBLY inLineLib

FROM 'D:inLineServerCLRSQLinlineCLRsqlinDebuginlineCLRsql.dll'

WITH PERMISSION_SET = SAFE



Everything works after those steps (which took some trial and error). I can create a sproc like:

CREATE PROC sp_test AS

EXTERNAL NAME inLineLib.[inlineCLRsql.test].PrintMessage

and it returns the Queue ID

Is there anything unadvisable about the steps above?



Thanks for your help



M



View 1 Replies View Related

Error Registering Assembly Using CREATE ASSEMBLY

May 1, 2008

We have written a test CRL stored procedure to test replacing one of our complex stored procedures but can€™t get it deployed to our SQL server that hosts a mirrored configuration of our production database (very locked down). It works fine on our development instances (not very locked down). It only references the default assemblies that were added when we created the project. All it does is use Context Connection=true to get data, loops though some records and returns the data using SQLContext. CLR is enabled on SQL server, the assembly is strongly signed, and we tried deploy using the binary string with the SAFE setting.


CREATE ASSEMBLY for assembly 'SQLCLRTest2' failed because assembly 'SQLCLRTest2' failed verification. Check if the referenced assemblies are up-to-date and trusted (for external_access or unsafe) to execute in the database. CLR Verifier error messages if any will follow this message
[ : SQLCLRTest2.StoredProcedures::GetLift][mdToken=0x600001e] Type load failed.
[token 0x02000008] Type load failed.

View 8 Replies View Related

Error: CREATE ASSEMBLY For Assembly

May 31, 2007

I am trying to deploy a Database Project with Visual Studio 2005 and SQL Server 2005 Standard.
I import €œSystem.IO€? and have therefore set the permission levels to EXTERNAL_ACCESS.

I am receiving the same error message that many folks have received.

CREATE ASSEMBLY for assembly 'Images' failed because assembly 'Images' is not authorized for PERMISSION_SET = EXTERNAL_ACCESS.
The assembly is authorized when either of the following is true: the database owner (DBO) has EXTERNAL ACCESS ASSEMBLY permission and the database has the TRUSTWORTHY database property on; or the assembly is signed with a certificate or an asymmetric key that has a corresponding login with EXTERNAL ACCESS ASSEMBLY permission. If you have restored or attached this database, make sure the database owner is mapped to the correct login on this server. If not, use sp_changedbowner to fix the problem. Images.

My CLR access is €œon€?

I have tried

1) From master run: GRANT EXTERNAL ACCESS ASSEMBLY to [BuiltinAdministrators].
2) From master run: GRANT EXTERNAL ACCESS ASSEMBLY to €œMy Windows Authentication ID€?.
3) Run ALTER DATABASE MYDATABASE SET TRUSTWORTHY ON
4) In Visual Studio .NET 2005 Set the permission levels to €˜external€™
5) Tried BuiltinAdministrators and my SQL Server Windows Authenticated Login ID for the ASSEMBLY OWNER.

I can compile BUT NOT DEPLOY

Any help would be greatly appreciated.
Regards Steve

View 8 Replies View Related

CREATE ASSEMBLY Using Assembly Binary?!?!

Mar 8, 2006

I was trying to understand how VS.NET2005 was deploying .NET CLR assemblies to SQL2005 so I ran a trace and found some interesting results.

VS.NET creates some SQL that looks pretty interesting:

CREATE ASSEMBLY [AssemblyNameHere]
FROM 0x4D5A90000300000004000000FFFF000......<continue binary data>
WITH PERMISSION_SET = EXTERNAL_ACCESS

Boy howdy!

I have tried to reproduce this and create my own deployment application but I cant figure out how they create this binary stream. The info in BOL is not much help and I have not found any samples anywhere on how to create this stream in c#.

Anyone out there been able to get this to work?

-Ben

View 4 Replies View Related

Notify Operator

Dec 2, 2006

Hello,

I have a problem with the notification. I have enabled Database mail and i have created an Operator.

Under SQL Server AgentJobs and then in the job properties i have enabled notification but i don`t receive a mail. Test e-mail works fine but "real" e-mail not.

I have also tried with the Database Maintenance Wizard but even then it just not work.

I have noticed that others have experienced the same problem but i have seen no solution yet.

Could you please help me? What can cause this problem? What`s the best i can do to start searching for the solution? Thanks!

View 6 Replies View Related

Notify By Email Two Different People For The Same Job

Jun 6, 2001

Currently, I have set up a SQL 7.0 database backup job and have one person notified if the job succeeds, but HOW do I choose an option to notify a different person if the job fails ?

Thank you in advance

View 5 Replies View Related

HELP! Jobs Fail To Notify

Sep 25, 2001

I can not get SQLServerAgent to Send Mail. Help!

SQLMail started successfully.

In the server agent properties I use the Test button and I receive the
response.
"Successfully started(and stopped) a mail session with this profile."
Indicating that mail should work.

If I send a email notification from a scheduled job it gives me the error:
NOTE: Failed to notify 'operations' via email

In the SQL Server Agent Error log I get.
"[264] An attempt was made to send an email when no email session has been
established"

xp_sendmail works fine.

Any ideas would be greatly appreciated.

TIA...

View 1 Replies View Related

How To Notify A DBA When An Object Is Created ?*V *?

Aug 14, 2000

Hi Guys,

Is there a way to notify DBA when a new stored procedure,table,view is created by any user...

Help is greatly appericated..

Jessi..

View 1 Replies View Related

Unzip Or Notify Failure

Oct 18, 2007

I have two question

1.In SSIS is there a way to unzip the text files
I have set an automated process in sql server agent
I receive ziped text files.I want to unzip the files before loading the data

2.Is there a way to notify when an error occurs in the package in sql server agent.

Please let me know



View 3 Replies View Related

Notify When Update / Insert

Mar 23, 2008

hi,
there is any way to a bd notify the user by creat a file or send a e-mail or even connect to a ip and send a message when any record is changed ( update/insert/delete)
i have seen a event called triger but i don´t know if is that what i want and i think this event can´t do what i need.
any one can help me?
thanks a lot

View 1 Replies View Related

How To Setup Sqlserver To Notify You Through E-mail?

May 25, 2001

I'm running sqlserver 2000 EE on windows nt 4.0 server. We are using
Microsoft outlook express. I would like to setup our sqlserver to
notify me via e-mail when a job finishes.

1) What value should I have for mail profile. Under
sql server age properties.

Please let me know.

Thanks,
Ranjan

View 1 Replies View Related

NOTE: Failed To Notify '' Via Email

Jan 5, 2004

I have job in SQL Server 2000 that is setup to notify an email operator upon successful completion.

When I test the notification to the set email operator it sends the email just fine.

When the job is run manually it emails the operator just fine.

When the job is run on a schedule it does not email the operator upon completion. It gives the details in view job history "NOTE: Failed to notify '<operator>' via email.

I have other jobs on the same server that run and notify via email to other operators upon successful completion just fine.

I have parsed MS Technet and the web and did not find anything.

Any help is greatly appreciated.

View 8 Replies View Related

SQL 2012 :: How To Notify External Application

Sep 17, 2014

When my SQL Agent job completes successfully, I'd like to send a notification to QlikView. The idea is to stop QlikView having to constantly check if the job has been run, and just get notified when it needs to update its data.

I don't know how to start. Can the job notifications push a success message to QlikView? I don't think I want to send an email, but something that indicates to QlikView to update the tables.

View 3 Replies View Related

Notify Operator Task Question

Nov 19, 2007



Hi,

can the Notify Operator Task send the output error message of its predecessor task(e.g Execute T-SQL Statement Task) to the operator? If yes, how?

Thanks,

Greg

View 11 Replies View Related

Notify Table Updates Across Servers

Nov 6, 2007



Simple question:

I have two servers S1 and S2. Inmediately after new data on S1 is available I want to perform some actions on S2.

I can use a trigger on S1, but if S2 is down the transaction on S1 will be lost. I could use database replication but I only need one single table in S1 to report changes to S2

Is there any other approach I could use?

Thanks.



View 1 Replies View Related

Using Database Mail To Notify Job Failures Help?

Sep 18, 2007

How do I get the option my database mail profile to appear in the drop down list on the "Notifications Page" in my job properties?

I have configured the mail profile and sucessfully sent a test E-mail.

I have also set "Enable mail profile" in the SQL Agent Properties and restarted the agent.

What else do I need to do, help please?

View 3 Replies View Related

Database Email Fails To Notify

Oct 8, 2007

I am havig trouble getting database mail to work. I setup IIS on the same box as sql. I setup SMTP with the relay to 127.0.0.0. In sql server, I setup database mail to point to localhost, with no authentication. After the setup, when I test the email (RMB Send test message) it works fine.

I created a job that will fail every time. I setup myself as the notify party on the job. When I run the job, it fails. I get no email. The job log has the following error:

Message
The job failed. The Job was invoked by User xxxxAdministrator. The last step to run was step 1 (test 1). NOTE: Failed to notify 'Dan Jones' via email.


I have spent lots of hours trying to make this simple thing work. What is wrong?

View 11 Replies View Related

Notify W/ SQLAgent Alerts That Disk Is Near Full

Jun 25, 2002

Does anyone know how to send a notification, using SQL Agent Alert,
if disk space gets to a certain level on the various server
hard drives?

thanks!

View 1 Replies View Related

SQL Server 2008 :: Notify Only If There Are Certain Blocks By Certain User

Jun 12, 2015

I'm trying to set the query to send email ONLY when it returns records of blocks and i cant seem to get this going.

declare @blocks varchar(max)
set @blocks = (SELECT spid,
sp.[status],
loginame [Login],
hostname,
blocked BlkBy,
sd.name DBName,

[Code] ....

View 1 Replies View Related

SQL Server 2008 :: Notify Operator Only Works Some Of The Time?

May 25, 2010

I've been working with Database Mail for some time but I haven't seen this one before. I have a maintenance plan that does the following:

1. Check database integrity
On Success:
2. Perform backups
On Success:
3. Perform a maintenance cleanup
On Success:
4. Notify operator of success

Steps 1 - 3 are also linked (via On Failure arrows) to a singular Notify Operator of Failure task.

The maintenance plan does exactly what I want it to, and if everything goes correctly, it successfully sends an email to an operator.

If steps 1 - 3 fail, the job ends in an error state, but does not trigger the Notify Operator of Failure task.

I was able to recreate the problem by creating another maintenance plan on the same instance with the same steps. Its "Notify Operator" on failure task also doesn't work.

It occurs to me that maybe I'm missing something, so here's some of the details of my SQL server:

SQL 2008 + SP1 (10.0.2531) x64 on Windows 2008 R2
DB Mail profile is public and default

I do have a slightly unusual profile, in that it uses two accounts:

1. A connection to a SharePoint SMTP service (where it catches emails directed at document libraries)

2. A connection to a UNIX-based smtp server (which routes mail to regular mailboxes and my SQL DBA mailing list)

The Profile will attempt to send to the SharePoint server first. The SharePoint server does not relay. If the document library email address doesn't exist, SQL will raise a warning (in the Database Mail log) and the profile will use the second account on the list, which is a real mail server and can relay the message to any mailbox.

It works really well, actually. When the maintenance plan completes successfully, the message is sent to the drop folder on the SharePoint server, and SharePoint routes the email to the correct library, and we have a central archive of all DB Mail notifications.

But if the job fails (for example, if the backup disk is out of space), none of this happens. According to the log, the job doesn't even try to send a notification. Looking at the DBMail log, the Mail service does not start. No email is delivered to the drop folder of the receiving SMTP server. So I don't think my Database Mail configuration is the problem here. It is apparently something to do with the way the job itself handles errors.

View 9 Replies View Related

Transact SQL :: Notify Only If Blocking Is Happening For More Than A Minute Or 30 Seconds

Aug 14, 2015

I have configured an alert like below to track all blocked events in SQL Server across all databases and then kick start a sql job when a blocking happens which inserts data to a table, when there is a blocking in SQL server , i get an email  --which is working fine and i am able to track all queries.

but, HOW to get notifications ONLY if BLOCKING IS HAPPENING FOR MORE THAN 30 SECONDS OR 1 MINUTE with out using sp_configure?

---ALERT
USE [msdb]
GO
EXEC msdb.dbo.sp_update_alert @name=N'Blocking Process', 
@message_id=0, 
@severity=0, 
@enabled=1, 

[Code] .....

View 4 Replies View Related

Assembly.Load Can't Load My Custom Assembly From The GAC.

Mar 7, 2007

Hi there.

I have an assembly, call it A1, that I've deployed to a SQL Server 2005 database. I can use the managed stored procedures from A1 in SQL Server no problem.

In A1 there is a bit of code which uses the Assembly.Load() method, so load another assembly and use instances of class found in that external assembly. However, when I run the managed stored proc in A1 that uses Assembly.Load() I get the error:

Could not load file or assembly 'A1, Version=1.0.0.0, Culture=neutral,PublicKeyToken='????' or one of its dependencies. The system cannot find the file specified.

(note: for security I've changed some of the above line).

So I changed the Assembly.Load() to use

System.Data,Version=2.0.0.0,Culture=neutral,PublicKeyToken=b77a5c561934e089

I re-built the project, re-deployed it and ran the code in SQL Server - it worked. I could create an instance of a System.Data.DataSet for example. So why can't I load my own custom assembly? My assembly does have a strong name and it's installed in the GAC. I wrote a console app to try and Assembly.Load() my custom assembly and that worked fine (it was also running on the same server as the SQL Server).

So it's defiantely the SQL Server that can't 'see' my customer assembly. What do I need to do this assembly so that SQL Server will allow me to Assembly.Load it, just as it can with System.Data?

Thanks
Jas.

View 1 Replies View Related

DB Mail And Notify Operator Through DB Mail Error Could Not Retrieve Item From The Queue

Feb 2, 2007

I've set up DB mail and sent a test e-mail and that comes through fine.

I set up an Operator with email Name: DWhelpton@k-and-s.com;MWeaver@k-and-s.com

I created a job and set up the notifications to e-mail the operator on failure.

When the job runs and fails, I do not get an e-mail and I get the following exception in the db mail log:

Date 2/2/2007 8:35:00 AM
Log Database Mail (Database Mail Log)

Log ID 402
Process ID 3936
Last Modified 2/2/2007 8:35:00 AM
Last Modified By NT AUTHORITYSYSTEM

Message
1) Exception Information
===================
Exception Type: Microsoft.SqlServer.Management.SqlIMail.Server.Common.BaseException
Message: Could not retrieve item from the queue.
Data: System.Collections.ListDictionaryInternal
TargetSite: Microsoft.SqlServer.Management.SqlIMail.Server.Controller.ICommand CreateSendMailCommand(Microsoft.SqlServer.Management.SqlIMail.Server.DataAccess.DBSession)
HelpLink: NULL
Source: DatabaseMailEngine

StackTrace Information
===================
at Microsoft.SqlServer.Management.SqlIMail.Server.Controller.CommandFactory.CreateSendMailCommand(DBSession dbSession)
at Microsoft.SqlServer.Management.SqlIMail.Server.Controller.CommandFactory.CreateCommand(DBSession dbSession)
at Microsoft.SqlServer.Management.SqlIMail.Server.Controller.CommandRunner.Run(DBSession db)
at Microsoft.SqlServer.Management.SqlIMail.IMailProcess.ThreadCallBack.MailOperation(Object o)


What step am I missing?

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







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