How Import XML File In A Table With Trigger.

May 10, 2007

Hello,
I'm trying to import a Xml file in a table.
It's working find, but when the data are inserted, my trigger on this
table doesn't work ?

I put my code below.

Best regards

Thank's

David


Xml file :
<?xml version="1.0" encoding="ISO-8859-1" standalone="yes"?>
<RTAVIS>
<FILENAME>03-05-073.PDF</FILENAME>
<idvir>1030</idvir>
<code>9219142</code>
<mnt>4337,88 </mnt>
</RTAVIS>


Xsd file :
<?xml version="1.0" ?>
<Schema xmlns="urn:schemas-microsoft-com:xml-data"
xmlns:dt="urn:schemas-microsoft-com:xml:datatypes"
xmlns:sql="urn:schemas-microsoft-com:xml-sql" >

<ElementType name="FILENAME" dt:type="string" />
<ElementType name="idvir" dt:type="string" />
<ElementType name="code" dt:type="string" />
<ElementType name="mnt" dt:type="string" />

<ElementType name="RTAVIS" sql:relation="ac_export_and_path">
<element type="FILENAME" sql:field="path" />
<element type="idvir" sql:field="numero_virement" />
<element type="code" sql:field="code_affilie" />
<element type="mnt" sql:field="montant_remise" />
</ElementType>

</Schema>

Vbs file:
Set objBL = CreateObject("SQLXMLBulkLoad.SQLXMLBulkLoad")
objBL.ConnectionString = "provider=SQLOLEDB.1;data
source=*****;database=*****;uid=*****;pwd=*****"
objBL.ErrorLogFile = "C:Temperror.xml"
objBL.SchemaGen = True
objBL.CheckConstraints = True
objBL.KeepIdentity = False
objBL.BulkLoad = true
objBL.Execute "C:Temp9219142_MAPPING.xsd", "C:Temp9219142.xml"
Set objBL = Nothing


Trigger source code :

CREATE TRIGGER [dbo].[trg_ac_export_and_path] ON
dbo.ac_export_and_path
FOR INSERT
AS

DECLARE @id AS varchar(50)

SELECT @id = 'A'+convert(varchar, [id]) FROM inserted

INSERT INTO ac_path([id], [path]) SELECT @id, path FROM inserted

END

View 4 Replies


ADVERTISEMENT

Import Txt File Into Sql Table Using Vb.net

May 3, 2007

hi!
my problem both concerns vb and sql. the problem is I have a text file delimited with semicolon. I have to enter this data into Sql table.
for example;
item description  ;code1;code2;code3;
there are too many lines like this. The code should enter the table these values.Table name is products, column names are desc,code1,code2,code3
I am using vb.net and sql server
thanks all!
 

View 13 Replies View Related

How To Import CSV File In To SQL Table

Apr 7, 2004

Any body know How to Import CSV file in to SQL table using asp.net

View 13 Replies View Related

Import Table To Csv File

May 28, 2008

hi
can any help
i have import table to csv file to append , replace, delete condition

View 5 Replies View Related

Import Csv File To Table

Nov 7, 2007

Hi.I would like to import the pprice.csv to table test3 on test database.
I've run this query:

BULK INSERT test..test3 FROM 'c:pprice.csv'
WITH (
FIRSTROW = 2,
MAXERRORS = 0,
FIELDTERMINATOR = ',',
ROWTERMINATOR = ' '
)


It has no error.but 0 rows effected.it means doesnt work correct.
what should I do?
thanks.
Amen

View 5 Replies View Related

How To Import Csv File Into A Table

Mar 18, 2008

hi,
i have a project requirement that i need to import csv file data into a table.
Please help me out?




Raghu sunkara.

View 3 Replies View Related

Import A Dynamic File Name Into A Known Table

Sep 26, 2006

How would I import a dynamic file name into a known table?I have the file name in a variable. So what object in SSIS do I use to do this. Thanks

View 2 Replies View Related

SQL 2012 :: Import XML File In Table

Jan 23, 2015

I want to import an XML file in an Table. The XML file is on an Other Network location than the Database server I’m connected to and I have access to this location with my windows Credential.

I connect from my local PC to the Database server “RS1” with my Windows Credentials.

There I run this script

CREATE TABLE XMLwithOpenXML
(
Id INT IDENTITY PRIMARY KEY,
XMLData XML,
LoadedDateTime DATETIME
)
INSERT INTO XMLwithOpenXML(XMLData, LoadedDateTime)
SELECT CONVERT(XML, BulkColumn) AS BulkColumn, GETDATE()
FROM OPENROWSET(BULK '<Networkname><MAP>Name_.xml', SINGLE_BLOB) AS x;

I Get the error:

Msg 4861, Level 16, State 1, Line 10
Cannot bulk load because the file "<Networkname><MAP>Name_.xml'" could not be opened. Operating system error code 5(Access is denied.).

(<Networkname><MAP>Name_.xml' is not the real name )

So it looks like the openrowset connects to the network location with other credentials.

Where I can find (and change) the credentials which is used to connect to the network location?

I found this article on MSDN (Security Considerations) but cannot find solution [URL] .....

View 1 Replies View Related

To Import CSV File Into Database Table

Jun 3, 2008

Hai all.,
Im trying to import the CSV file values using bulk insert but im getting an error in my code .so can anyone help me on this.
the following is the coding i have created
--create table
CREATE TABLE CSVTest
(ID INT,
FirstName VARCHAR(40),
LastName VARCHAR(40),
BirthDate SMALLDATETIME
)
--import from CSV using bulk insert

BULK
INSERT CSVTest
FROM 'c:csvtest.txt'
WITH
(
FIELDTERMINATOR = ',',
ROWTERMINATOR = ''
)
GO

im gettin an error like
Msg 4860, Level 16, State 1, Line 1
Cannot bulk load. The file "c:csvtest.txt" does not exist

The thing is i have created a CSV file in C drive with some values.

Thanks in advance

View 6 Replies View Related

Import Excel File Into Table Via T-SQL?

Jun 6, 2008

Hi folks. I am having an excel file. I need to import this file to database and update some other tables with data contained in this file. I would like to automate this process as much as possible.
Now, I am just using SQL Server Import Wizard to create a table and then I am running an update query. Is there any (more automate) way to do this?

Thanks for your time.

View 3 Replies View Related

How To Create Table On Text File Import?

Sep 27, 2007

Hey guys,
I have a dilemma and hope someone can help.

I don't know of any utilities or commands in SQL that do this but I hope someone does.

What I need to do is something like a bcp import a text file in. I can do that with DTS as well. But what I wanted to do is create a table on the import. So lets say, I am importing a tab-delimited file with column names as the first row that is called ax.txt. On import, it would create the table ax with the column names in the file and then import the data into that table.

I hope I explained it clearly. Please let me know if there is anything I can use to do this without writing lots of code.

I have an idea how to do it the long way but hope there is a utility that already does it.

Thanks in advance.

View 10 Replies View Related

Import A CSV Delimited Text File Into A Table

Jan 18, 2007

Hi,

Could you help me to write a script to import a CSV delimited text file into a sql server table.?

Thanks,



carlos

View 2 Replies View Related

Import A Text File To A SQL Table Question

Feb 6, 2008

Greetings all!

I am a relative newbie to SQL but I've written many queries for vb.net/.net code...I'm not an absolute beginner.

I'd like to import a text file into a sql database so that I can use SQL Reporting Services to report on the data. Here is a sample of the first 8 textfile records. All of the 6 potential database fields are separated by a comma and no spaces:

1,12/4/06 4:12:11 PM,67.13,70.50,71.56,8.23
2,12/4/06 4:17:11 PM,67.13,70.50,71.56,8.33
3,12/4/06 4:22:11 PM,67.19,70.69,71.69,8.19
4,12/4/06 4:27:11 PM,67.19,70.63,71.69,8.18
5,12/4/06 4:32:11 PM,67.19,70.69,71.75,8.05
6,12/4/06 4:37:11 PM,67.19,70.69,71.69,8.03
7,12/4/06 4:42:11 PM,67.19,70.63,71.69,8.05
8,12/4/06 4:47:11 PM,67.19,70.63,71.63,8.02

The description for field datatypes of the first record above is:

1 (this is an autonumber, should be a number for ordering)
12/4/06 4:12:11 PM (date and time, can be converted to text if necessay)
67.13 (number, 2 decimal spaces)
70.50 (number, 2 decimal spaces)
71.56 (number, 2 decimal spaces)
8.23 (number, 2 decimal spaces)

The textfile is big, 97K records. I have SQL 2005 installed on my PC.

Can anyone out there please help me with the import or SQL statement to create a SQL table from this? Any help would be greatly appreciated!

Thanks and have a great day - gad1



View 5 Replies View Related

Import Text File To Sql Table In Sql Server 2005

Mar 7, 2008

hi guys
i need  to import text file to sql table in sql server 2005 ...using query how do i import text file to sql table .......................
 i need query
i dont want go Import/export options

View 1 Replies View Related

Looking For SQL To Import Asii File Data Into Vendors Table

Sep 16, 2005

I have tried  my file name vendor_insertFromFile2.sqlBULK INSERT  (dbo.vendors VendorName, Street, City, Region, Country, PostalCode, Telephone, PortalId, Fax, Email, Website, CreatedDate, Unit, LastName, Cell) from 'D:AccessNAICSxPortal0_SampleData.txt'error messageServer: Msg 170, Level 15, State 1, Line 2Line 2: Incorrect syntax near '('.Data in the "CompanyName","Address","City","State","country","fullzip","FullPhone","Portal","Fullfax","Email","URL","date","ID","Contact_1","800No""DAVID STRAWN","460 FLOWERING TRL","GRAYSON","GA","United States","30017?,"770-277-8709",0,"“,"bkroom@bellsouth.net","WWW.BACKROOM4MEN.COM","09/02/05",1,"DAVID STRAWN","BRADRUSS","3353 S MAIN ST STE 130","SALT LAKE CITY","UT","United States","84115?,"801-975-0374",0,"“,"rusbrad@msn.com","WWW.BADANDNASTY.COM","09/02/05",2,"BRAD JENSEN",Thanks in advance on what is wrong or a link with working examples

View 2 Replies View Related

How Can I Export/import Data On Table To/from Text File

Dec 24, 1998

I needs export data on table to text file so I can process this data
with another database engine ie. Informix.

Can anybody help me to solve this problem ?

View 2 Replies View Related

Stored Procedure - Import CSV File Into Table In Excel

Mar 3, 2014

I have the following code to import .csv file into my table in excel. It's being inserted into a table. dbo.ImportedPromoPricing. Table and the .csv file have 3 fields price, code and selling price.

Once import is completed I want to use the data in my dbo.ImportedPromoPricing to update another table dbo.MasterPricing. Records need to be compared and updated or appended if needed. in case of update only price will be updated. this is the beginning of my code

USE [Reporting]
GO
/****** Object: StoredProcedure [dbo].[ImportPromoPricing] Script Date: 03/03/2014 14:04:01 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON

[Code] .....

View 2 Replies View Related

SQL 2012 :: Import Txt Data File Into Temp Table?

Sep 30, 2014

In Access, I can import a txt file data(e.g. Claims.txt) as below specifications:

Choose the delimiter that separates your fields: Other (|)
First row contains field name: Yes
Text Qualifier:"

I need to create a store procedure to read txt file data (d:cliamcliams.txt) first column (ClaimNumber) into a temp table (#claim)

(This #claim table will use for my .Net program)

There about 5 txt files need to process every day.

View 1 Replies View Related

How To Import Data Using Bcp Without A Format File Or Table Layout

Mar 20, 2008

I have several bcp output files I need to import into tables. I do not have format files for them. As far as I know they are in native format. I do not know the layout of the destination table they would populate.

1) how can I determine from the bcp file itself the schema of the destination table? Once I know that I should be able to import the data into the table.

Thanks

View 6 Replies View Related

How To Import Text File Using The Exising Table Schema

May 28, 2008

Hello;

I have table schema and text data file. After create the table, and then import the text data file. However, the text file always overwrite the table schema.

How could I using existing table schema to import the text file?

Thanks,

View 10 Replies View Related

Import Data From Text File Into A Temp Table In Stored Proc

Oct 1, 2001

Hey,
can one of you please show me how to import data from a text file into a temp table in a stored proc.
thanks
Zoey

View 1 Replies View Related

How Do I Import A Varying Column Width Flat File Into A Table Using SSIS?

Apr 24, 2008

How do i import a Varying Column Width Flat file into a Table using SSIS?


I have a flat file that has 4 columns with varying width
Like I should read the file as
Col 1 - (1 to 10 Characters)
Col 2 - (12 to 21 Characters)
Col 3 - (22 to 35 Characters)
Col 4 - (36 to 38 Characters)
At the end of the record is a "LF"


I think "Fixed Width" Columns allow me to define a standard column length for all the columns.. Right?

Any thoughts on how to?

View 9 Replies View Related

Integration Services :: How To Import Filenames And File Creation Date Into Table

Apr 20, 2015

I am importing Differennt Excels Files into table. my require ment is after importing completed I need to insert all these Filenames ,File creation date into table. (for Auditing).

View 9 Replies View Related

Integration Services :: SSIS - Import Date From File CSV Into Table If It Doesn't Exist

May 6, 2015

I created a simple SSIS package that takes a Flat File Source (CSV file) and Imports it into a OLE DB Destination ([TestCSVImport].dbo.Table1). I have other CSV files I'd like to import, but I don't want to import entries where column "ordereID" (PK) are the equal. Just want to import the new data found in the CSV files. I tried adding a Lookup in-between the Flat File Source and the OLE DB Destination, but I'm not sure how to accomplish only importing new data.

View 2 Replies View Related

SQL Server 2008 :: Bulk Import And Create New Table Based On Header Fields Of Imported File (XLXS)

Sep 11, 2015

I have a record in an Excel format (Excel 2010) and I would like to bulk import that into SQL Server 2008 and also while importing, SQL Server will automatically create a new table based on the header fields or row of the source file.

I am not sure if SQL Server 2008 has this capabilities.

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

Error Regarding File Import Through Import Wizard

Jan 12, 2006

Hi all,

when trying to ímport files to our database server from a client, I keep getting an error:

- Validating (Error)
Messages
Error 0xc00470fe: Data Flow Task: The product level is insufficient for component "Source_txt" (1).
 (SQL Server Import and Export Wizard)
 
Error 0xc00470fe: Data Flow Task: The product level is insufficient for component "Data Conversion 1" (175).
 (SQL Server Import and Export Wizard)

... doing the same import when logged on the server, hasn't been giving me any errors, how come. I can from my client without trouble import tables from other DB servers but when ever it is files it won't do it.

 

I tried as mentioned in other threads rerun setup to re-install SSIS, but as it was already installed it wouldn't re-install. My next move would be to make a clean install, but not sure it would help, as I think this is a buck.

best regards

 

Musa Rusid

View 1 Replies View Related

Exported Flat File Data Will Not Import To Same Table Without Extensive Data-type Manipulation

Jul 13, 2007

I'm moving data between identical tables and have to use a flat file as an intermediary. I thought: "No problem, SSIS can do a quick export to a file, then move the file to another server, then use SSIS to import the data to the new server."



Seems simple, right?



I'm hitting all sorts of surprising data conversion errors. I used the export wizard to create the export package. This works fine. However using the same flat file definition, the import package fails -- even when I have no destination. That is I have just one data flow task that contains only one control: the Flat File source. When I run the package the flat file definition fails with data type conversion and truncation errors. One of the obvious errors is for boolean types. The SQL field is a bit, SSIS defined the column as DT_BOOL, the output of the data are literal text values "TRUE" and "FALSE". So SSIS converts a sql datatype of bit to "TRUE" and "FALSE" on export, but can't make the reverse conversion on import?



Does anyone else find this surprising? I would expect that what SSIS exports, it can import given all the same table and flat file definitions. Is SSIS the wrong tool to do such simple bulk copies? I'd like to avoid using BCP because this process will need to run automatically within SQL Agent so we can leverage all the error tracking and system monitoring.



View 12 Replies View Related

SQL Server Import And Export Wizard Fails To Import Data From A View To A Table

Feb 25, 2008

A view named "Viw_Labour_Cost_By_Service_Order_No" has been created and can be run successfully on the server.
I want to import the data which draws from the view to a table using SQL Server Import and Export Wizard.
However, when I run the wizard on the server, it gives me the following error message and stop on the step Setting Source Connection


Operation stopped...

- Initializing Data Flow Task (Success)

- Initializing Connections (Success)

- Setting SQL Command (Success)
- Setting Source Connection (Error)
Messages
Error 0xc020801c: Source - Viw_Labour_Cost_By_Service_Order_No [1]: SSIS Error Code DTS_E_CANNOTACQUIRECONNECTIONFROMCONNECTIONMANAGER. The AcquireConnection method call to the connection manager "SourceConnectionOLEDB" failed with error code 0xC0014019. There may be error messages posted before this with more information on why the AcquireConnection method call failed.
(SQL Server Import and Export Wizard)

Exception from HRESULT: 0xC020801C (Microsoft.SqlServer.DTSPipelineWrap)


- Setting Destination Connection (Stopped)

- Validating (Stopped)

- Prepare for Execute (Stopped)

- Pre-execute (Stopped)

- Executing (Stopped)

- Copying to [NAV_CSG].[dbo].[Report_Labour_Cost_By_Service_Order_No] (Stopped)

- Post-execute (Stopped)

Does anyone encounter this problem before and know what is happening?

Thanks for kindly reply.

Best regards,
Calvin Lam

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

Using SQL SERVER IMPORT WIZARD, Why Trigger Not Working?

Mar 21, 2008



Hi SQL Proz,

I am trying to important some data in the an existing table with trigger. Unfortunately, the data were successfully inserted into the said table but the trigger did not work out. Why? How to do the tricks?

Many Thanks!

View 2 Replies View Related







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