Smart Trigger...

Oct 10, 2007

Hello forum.
I have a problem that is kill me.
Initial dates: a table (Tbl_1) to collect dates from users (within form in VB), a view (View_1) to compute some columns (is a part from business€™ logic) and a table (Tbl_2) designated for a trigger.
I will try to resume the contents of above table€¦
create table Tbl_1
(
id int not null,
code varchar(10) null,
TBO int not null, -- (Time between Overhauling)..hours (life cycle)
T_Hrs_AtLastOvh int null, -- total running hours from last overhauling
TRH int null, -- total running hours (the life of equipment)
)
GO
Create view View_1
as
select code, [TBO]-([TRH]-[T_Hrs_AtLastOvh])as HrsTo_NextOvh
from Tbl_1
GO
create table Tbl_2
(
id int not null,
code varchar(10) null,
Start_dt smalldatetime,
Stop_dt smalldatetime,
)
GO
--drop table Tbl_1
--drop view View_1
--drop table Tbl_2

Let to insert some dates into Tbl_1:

Insert into Tbl_1
select 1,'cod1',2000,2500,3000
union all
select 2,'cod2',3000,4000,7000
union all
select 3,'cod3',1000,2000,2000
union all
select 4,'cod4',1500,3000,3000
GO
The result of View_1 is in Fig.1:






Fig.1






cod1

1500


cod2

0


cod3

0


cod4

2500




cod1

1500


cod2

3000


cod3

0


cod4

2500







Fig.2





The operator perform requested job for the equipment and the life cycle starts counting again. Suppose to have:

Update Tbl_1 set T_Hrs_AtLastOvh=7000 where id=2
GO
The result of View_1 is Fig.2.
I wish to insert (within trigger) into table Tbl_2 all codes that have [HrsTo_NextOvh]=0 from View_1 and automatic to record the date when the record is done with a propertie like €™starting job€™.
After the operator executed the job, he will update the Tbl_1 (the result is in Fig.2) and the trigger has to record this process with the propertie like €˜completed job€™.
Depending by the time between overhauling and the operating hours of equipments, this task happens more or less often.
My intentions are to record the time requested to executed a job and to make a history of events.

Any suggestion to solve my problem is full apreciated.

View 6 Replies


ADVERTISEMENT

Who's Smart Enough To Figure This Out?

Mar 9, 2004

Hello All,

I've been trying to get a range of values out of my SQL Server 2000 db without sucess. The field in question has the data type of char(8) and looks like this:

House_numbr_pub (leading spaces in front of each value)
140A
140
141
142
143
144
145
146
147
148
149
150
151
.
.
.
14500
.
.
.

Does anyone know how write a sql statement that will return 140-150, but excluding the ' 14500' and 100-1000. I tried the following where clause to return a range between 100-1000.

WHERE (cook.STREET_PUB LIKE 'lincoln%') AND (LEN(LTRIM(cook.HOUSE_NUMBR_PUB)) BETWEEN 3 AND 4) AND (
(LTRIM(cook.HOUSE_NUMBR_PUB) >= '100') and (LTRIM(cook.HOUSE_NUMBR_PUB) <= '1000') )

This where clause only return two records (100 and 1000). I want it to return 100-1000.

I also tried the following where clause:

WHERE LTrim(cook.HOUSE_NUMBR_PUB) like '1[45][0-9]'
OR
LTrim(cook.HOUSE_NUMBR_PUB) like '1[45][0-9]'

However, building this on the fly with .net will take some effort if someone is trying to search range 1-10000000.


Please Help,

James

View 3 Replies View Related

Writing Smart SQL

Oct 25, 1999

Is it possible to do the following without cursors or creating an identity column:

I have a table from legacy data with ~ 1 million records. I need to insert this into the new table which has a unique varchar(11) key. For the new system this key is generated by calling a SP that returns the next key in sequence. To put the legacy data records in the same table I want to first create a new column at end of legacy data table and populate this using SQL without going thru using cursor and calling the SP for each and every record to get a unique varchar(11) key.

In short here is what I want:

Field1 Field2 varchar(11)key

------ ------ -----------

jsdhf dsf99 1LEG

878jh whjhj 2LEG

8728jh whjhj 3LEG

8578jh whjhj 4LEG

3878jh whjhj 5LEG

6878jh whjhj 6LEG

8508jh whjhj 7LEG

...

...

...

4878jh whjhj 1000000LEG

How do I generate this key using an SQL stmt?

Thanks in advance,

Nishi

View 4 Replies View Related

Smart Aggregation

Jan 1, 2007

I'm having problems implementing the following in reporting services 2005.

My hierarchy looks like this (just to illustrate the problem...):

University->Student->Exam

My query returns the following fields:

University,Student,StudentPayment,ExamName,ExamScore

I need to create a report that will show the hierarchy and to smartly aggregate the StudentPayment to both the Student and the University levels.

The problem is that the StudentPayment field is being multiplied by the number of exams in the upper level aggregation.

If only I could set the granularity level of the StudentPayment measurement...

Note that I don't have access to the query, so I can't change anything on that front.

Thanks,

Efi

View 6 Replies View Related

REAL CHALLENGE For The Smart One

May 8, 2002

Hi,
tell me please how I can trace the modification on the table such as "insert" record into one and syncronize mirror table at the same time once the insert has happend, BUT - no indexes no trace jobs, no any modification or objects on the master table... ha?

View 5 Replies View Related

Thoughts About The Smart Way To A Task

Jul 20, 2005

I'm still a database newbie so I would like to solicit thoughts aboutthe smartest way to do something in sqlserver.My company has a web application that we customize for each client.We can do this because everything is database driven. We havedatabase tables that contain our HTML and database tables as well assome standard tables for each database. We have an in house app thatlets us tweak both of these things and creates a new web site anddatabase tailored to each project.Each of these sites has a table that stores a schedule are clientsuse.The records in this schedule table change when information in othercustom generated tables change.My company currently uses a legacy foxpro app to update the scheduletable.The foxpro app contacts sqlserver, reads a table with a list of tablesand scheduling information to check, checks each of those items andupdates the schedule table.I would like to lose the foxpro app.At first thought.........as a database newbie.......putting triggersin each of the tables to update the schedule when something changesseems the way to go.However, since we change a part of the schema ( we have an app thatgenerates the database tables unique to each client ) for each clientI would like a scheme that would not involve having to create adifferent trigger for each new table.I would also like something that updates in real time. Right now thefoxpro app is executed once a day.I was thinking of making a large stored procedure and putting anidentical call to that procedure in each table.Each table would have the same trigger in it that would get fired whenthe record was altered. It would call the stored procedure withrelevent arguments to update the schedule.Does this sound like a smart way to solve this problem or am I notthinking "database enough"?Any thoughts are welcome.I would like to build a better solutionSteve

View 1 Replies View Related

Win CE 4.2 And Smart Dev Application Question

Apr 18, 2006

I'm a bit stuck with this one... hope someone can help.

I'm trying to develop an application that will run on a pocket PC with Windows CE 4.2

I'm using .Net 2003 and the application is in VB.Net.

I can run the application on the pocket pc fine (ie. form paints, buttons work) , until I need to connect to Sql DB on the server.

When I try to create a connection object (Dim dbconnection As New SqlClient.SqlConnection)

I get an error stating .. "This application (test.exe) requires a newer version of .Net Compact Framework than the one installed on the device" .... "could not load System.Data.SqlClient.SqlConnection from assembly System.Data.SqlClient Version=1.0.5000.0"

The version that it is looking for is. 1.0.5000.0 . The VS2003 is using this version.

I've downloaded the compact framework v1. sp3 , ran all the cabs on the Win CE device ... it looked that it installed fine.... but the problem still exists.

Help Please..

Derek

View 12 Replies View Related

SQL 2012 :: What Is The Concept Of Smart Backup

Jul 6, 2015

what is the concept of smart backup in sql ?

View 1 Replies View Related

SQL SERVER EXPRESS - Vb.net/smart Client

Oct 16, 2006

Hey all... great site!

Here's what I'm going for:

I have an 05 VB.NET windows application that will be used as a smart client for our folks in the field. The windows application includes 05 SQL Server Express. I have included in the Data Sources of my project and attached file going through the wizard Microsoft SQL Server Database File (SqlClient) ='s (myfile.mdf) and then selected all tables, views, stored procedures, and functions... the corresponding myfileDataSet.xsd with the myfile.mdf are now located in the root of the project. I now recompile the project without error and go to the properties section Publish tab... select the Application Files button and myfile.mdf Publish Status is set to Include and the Download Group set to Requried. With this in place I right click on the myfile.mdf from the Soultion Explorer and under the properties section have set the build action to compile and use the copy always setting for the Copy to Output Directory.

My app.config looks like this:

<configSections>
<sectionGroup name="userSettings" type="System.Configuration.UserSettingsGroup, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
<section name="myfile.My.MySettings" type="System.Configuration.ClientSettingsSection, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" allowExeDefinition="MachineToLocalUser" requirePermission="false" />
</sectionGroup>
</configSections>
<connectionStrings>
<add name="myfile.My.MySettings.ffgscrmConnectionString" connectionString="Data Source=.SQLEXPRESS;AttachDbFilename=|DataDirectory|myfile.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True"
providerName="System.Data.SqlClient" />
</connectionStrings>

After the publish is completed on the client machine... install for Windows Installer 3.1, SQL Server Express, and the Windows Application contains no data but everything else works fine.

My problem is that I need to attach the myfile.mdf to the new SQL Server Express instance on the client machine during the installation process so that when the application fires it will be pointed to the above location on the client.

Any ideas... scripts... includes for an ApplicationEvents.vb on how to do this? Thanks a ton... :)

Kind regards,

BillB

Your mind is like a parachute.. It has to be able to open, for it to work.

View 1 Replies View Related

Why Optimizer Is Not Smart? Is Dynamic SQL My Only Option...

Feb 8, 2007

declare @ContactId as integerset @ContactId = 5select *from Person.Contactwhere ContactId = @ContactIdOR @ContactId = -1If you run this in SQL 2005 on the AdventureWorks database,why the logical reads is 561Table 'Contact'. Scan count 1, logical reads 56and not 2 when you run without the second OR condition:declare @ContactId as integerset @ContactId = 5select *from Person.Contactwhere ContactId = @ContactIdHow can i use the same SP and either get one record returnedby passing the ID of the field, or pass a dummy parameter like-1 in order to get ALL the records returned.In this case even when i pass a parameter like ContactID = 5there is still a table scan (clustered index scan in this case)happening for the other OR condition.There's no method to tell SQL to start checking the first conditionwhether or not it is true then if it is false then check the second ORconditon. On the same topic does this mean all OR conditions areALWAYS verified regardless if one of them has already been determinedto be True?Thank you

View 2 Replies View Related

My First Post: Smart SQL Updating Technique..??

Jul 12, 2007

Hello geniuses



First of all I would like to announce that this is my first time I post here.. However, I'm pretty sure that I'm in the best place to ask what I want. To cut the story short, I'm querying SQL database on a remote machine and having the result saved (mapped) to another table on another database on the same remote machine. The thing is the destination table was empty before the query was run the first time. I have been searching for some smart way so that when I modify the source tables that my query is based on, it doesn't affect except the modified rows. In other words, it should be like if the row is already there, do nothing. otherwise, it updates the existig record. else, it's a new record and it's inserted. I think what i need will include some coding for sure, yes? I don't know if i'm clear about the requirement or not though! but I know that you are experts and can direct me. Waiting for your valuable replies.



Sherif Magdi

View 11 Replies View Related

Vs 2008 Smart Device Cab Project And Sqlce 3.5

May 21, 2008

I've created a simple application that uses a SQLCE 3.5 database. When I debug it SQLCE 3.5 is deployed to the emulator. However, I made a "smart device cab project" for my application and copied the cab file to my windows mobile 6 device and it does not deploy SQLCE 3.5. I don't see a way to specify the prerequisites of the "smart device cab project" like you can in a normal setup project. How can I get SQLCE 3.5 to deploy with my application...or even just get it on my device? I've tried installing it on my desktop with the device connected via active sync, but it doesn't install on the device like the compact framework did.

View 3 Replies View Related

Setting Up A Web Synchronized Subscription For A Smart Client

Nov 20, 2005

So in a previous thread I discovered that in order to actually subscribe to any publication, the publisher needs to be a well-known network name, requiring DNS resolution. You can't simply point a SQLExpress instance at an ip addressinstance and have it resolve the communications.

View 5 Replies View Related

Updating Database From A Smart Device Application

May 24, 2007

i m developping a smart device application with vb.net

i m using the following code from:

http://msdn2.microsoft.com/en-us/library/aa454892.aspx

(i still working on the first exercice and i'm following it step by step)

everything is working properly

i was advised to add this code when closing the form1

Try

Me.ContactsBindingSource1.EndEdit()

Me.ContactsTableAdapter1.Update(Me.TestDataSet1.contacts)

MsgBox("Update successful")

Catch ex As Exception

MsgBox("Update failed")

End Try



the problem is:

should this code update the database created with sql server 2005

if yes why isnt it working here

and should the database be replicated on my emulator before it is updated

(in this exercice i do not have a database storerd in the emulator)

plz i urgently need the answer

View 4 Replies View Related

Smart Client - Data Centric - SQL 2K To SSE Local

Jul 4, 2006

Trying to develop a smart client which will have data centric approach for storage of local data. The server is SQL Server 2000 and foot print database is going to SQL Server Express 2005. Is Merge replication a vaiable option. Can somebody guide me on this approach

Is there any other architecture proposed for Smart client arcjitecture where the data tranfer will be in a couple of GBs. Can somebody tell me more about SOA as well

Thanks!

View 4 Replies View Related

Finding Duplicate Entries In A Smart Way - By Comparing First Two Words

Jul 20, 2005

What is the best way to compare two entries in a single table wherethe two fields are "almost" the same?For example, I would like to write a query that would compare thefirst two words in a "company" field. If they are the same, I wouldlike to output them.For example, "20th Century" and "20th Century Fox" in the companyfield would be the same.How do I do this? Do I need to use a cursor? Is it as simple as using"Like?"

View 2 Replies View Related

Smart Device CAB Project Detected Dependencies Not Included?

Jul 5, 2006



Hi

I have created a Smart device application for Windows CE 5.0 device using Visual studio 2005 and i have added the smart cab project to the solution. When I add project out in teh appllication folder, the detected dependencies are not included. Instead dependent files appear with red circle in solution explorer.

My project uses .Net Framework 2.0 and SQL Server mobile 2005 and SQL Server mobile database file and some symbol files

I need included all of them in my cab project and when user clicks on it (in the device) it should install all of them.

Let me know why detected dependencies are not included in the Cab project and how can get all the above mentioned things to be installed along with my program



Regards

Mani

View 4 Replies View Related

Configuring SQL Express During Installation And Attaching Smart Client DB / Silent Install For One Click?

Oct 9, 2006



Hey all,

Cool place! Has anyone deployed SQL Express silently using one click and an attached a smart client DB from within the app ... would love to see some of the best practices or horror stories! Just kidding... :) I'm about to deploy a smart client using SQL Express and could use some tips from someone who has been there.

Thanks in advance,

Bill

View 7 Replies View Related

.Net Framework 3.5 Smart Device Project Deploys The .Net 2.0 SQLClient When Both Vs2008 And Vs2005 Installed

Feb 19, 2008



I have both vs2005 and vs2008 installed. I'm working with a .Net Compact Framework 3.5 Smart Device Project.

If I refrence the System.Data.SqlClient.dll (Version 3.0.3600.0 Runtime v2.0.50727)
C:Program FilesMicrosoft SQL Server Compact Editionv3.5DevicesClientSystem.Data.SqlClient.dll

When I deploy the application I get an error ".Net Compact Framework v2.0 could not be found Please install it and run the setup again"

Studio is :
Deploying 'C:Program FilesMicrosoft Visual Studio 8SmartDevicesSDKSQL ServerClientv2.0wce500ARMV4isql.ppc.wce5.armv4i.CAB'

We tested this on a PC without vs2005 and it seems to work fine.

Any suggestions?


jlj

View 3 Replies View Related

Reporting Server Is Not So Smart As Analysis Server

May 11, 2007

Hi,

I have a fact table with 2 columns value A and value B

In Analysis server I add a calculated column C as A / B

Now my data looks like this

A B C

0 10 0

5 10 0.5



If you add totals in Analysis server you get

5 20 and 0.25 which is correct



If you add totals in Reporting server you get

5 20 and 0.5 which is not correct.



How can I fix this ?



Thanks in advance



Constantijn

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

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

How To Create New CLR Trigger From Existing T-Sql Trigger

Mar 18, 2008

how to create new CLR trigger from existing T-Sql Trigger Thanks  in advance

View 3 Replies View Related

Modifing The Row That Invokes A Trigger From Within That Trigger

Jul 23, 2005

When a row gets modified and it invokes a trigger, we would like to beable to update the row that was modified inside the trigger. This is(basically) how we are doing it now:CREATE TRIGGER trTBL ON TBLFOR UPDATE, INSERT, DELETEasupdate TBLset fld = 'value'from inserted, TBLwhere inserted.id= TBL.id....This work fine but it seems like it could be optimized. Clearly we arehaving to scan the entire table again to update the row. But shouldn'tthe trigger already know which row invoked it. Do we have to scan thetable again for this row or is their some syntax that allows us toupdate the row that invoked the trigger. If not, why. It seems likethis would be a fairly common task. Thanks.

View 4 Replies View Related

Disabilitazione Trigger [DISABLE TRIGGER]

Jul 20, 2005

Salve, non riesco a disabilitare un trigger su sqlserver nè da queryanalyzer, nè da enterprise manager.In pratica tal cosa riuscivo a farla in Oracle con TOAD, mentre qui nonriesco.Mi interessa disattivarlo senza cancellarlo per poi riattivarlo al bisognosenza rilanciare lo script di creazione.Grazie a tuttiHi I need to disable a DB trigger and I'm not able to do this neither withquery analyzer, neither with enterprise manager.I remeber this job was quite simple using TOAd in Oracle.I'm interested in making it disabled not delete it, without run creationscript.Thanks a lot to everybody.

View 4 Replies View Related

Update Trigger Behaviour W/o A Trigger.

May 30, 2008

Hi,
I am not sure if this is the right forum to post this question.
I run an update statement like "Update mytable set status='S' " on the SQL 2005 management Studio.
When I run "select * from mytable" for a few seconds all status = "S". After a few seconds all status turn to "H".
This is a behaviour when you have an update trigger for the table. But I don't see any triggers under this table.
What else would cause the database automatically change my update?
Could there be any other place I should look for an update trigger on this table?
Thanks,

View 3 Replies View Related

Drop Trigger With A Variable Trigger Name

Sep 20, 2007



Hi all in .net I've created an application that allows creation of triggers, i also want to allow the deletion of triggers.
The trigger name is kept in a table, and apon deleting the record i want to use the field name to delete the trigger

I have the following Trigger

the error is at

DROP TRIGGER @DeleteTrigger

I'm guessing it dosen't like the trigger name being a variable instead of a static name
how do i get around this?

thanks in advance

-- ================================================

-- Template generated from Template Explorer using:

-- Create Trigger (New Menu).SQL

--

-- Use the Specify Values for Template Parameters

-- command (Ctrl-Shift-M) to fill in the parameter

-- values below.

--

-- See additional Create Trigger templates for more

-- examples of different Trigger statements.

--

-- This block of comments will not be included in

-- the definition of the function.

-- ================================================

SET ANSI_NULLS ON

GO

SET QUOTED_IDENTIFIER ON

GO

-- =============================================

-- Author: <Author,,Name>

-- Create date: <Create Date,,>

-- Description: <Description,,>

-- =============================================

CREATE TRIGGER RemoveTriggers

ON tblTriggers

AFTER DELETE

AS

BEGIN

-- SET NOCOUNT ON added to prevent extra result sets from

-- interfering with SELECT statements.

SET NOCOUNT ON;

Declare @DeleteTrigger as nvarchar(max)

select @DeleteTrigger = TableName FROM DELETED



IF OBJECT_ID (@DeleteTrigger,'TR') IS NOT NULL

DROP TRIGGER @DeleteTrigger

GO

END

GO

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

Trigger Not Execute Some Data Or Insert Not Execute A Trigger For Some Data

Mar 3, 2008

I have trigger, but not execute somedata because insert few row in every second. I use java to insert data to SQL server 2005. Data inserted to a table but not executing trigger for some data.
For example 100 data every second inserted to a table.

If insert data one by one to a table trigger fires success.
Please Help me.

View 1 Replies View Related

Sp Name In Trigger

Jun 17, 2006

There are two different Stored Procedures insert data into a table, is it possible to catch what stored procedure name was that trigged the trigger in the trigger?

View 1 Replies View Related







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