Call A DLL Or EXE File From SQL Trigger

Mar 22, 2007

I need some help calling a DLL or EXE from a SQL Trigger.  I have the trigger set up, except I have no clue how to call a DLL or EXE or if it is even possible.  Here is what I have for the Trigger so far: 






-- ================================================
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
CREATE TRIGGER CallProgIfParentID
ON Toc
FOR INSERT
AS
IF ((select ins.[ParentID] FROM inserted ins) = '57660')
-- I want to be able to programmatically change '57660' from an ASPX page
EXEC
-- This is where the call function goes
GO







Another question I have is can a trigger be created programmatically using ASPX pages written in VB.NET in VS2003?

Thank you in advance

View 7 Replies


ADVERTISEMENT

T-SQL (SS2K8) :: Trigger To Call A Program To Write Text File Onto A Folder In Server

Apr 29, 2014

I have created a trigger to call a program that is written by our program. The program is basically read the record in the table and write to a text file, then delete the record from the table.

The trigger is a after insert trigger. After we added the trigger, we insert a record to the table. The result is that the record still and did not get deleted. Also, the text file didn't get created either. It seems that it take a long time for the record to be written to the table.

But if we just run the program (a exe file), it can write a text file in the folder and delete the record. the trigger is basically:

USE [Zinter]
GO
/****** Object: Trigger [dbo].[ZinterProcess] Script Date: 04/29/2014 18:34:56 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

[Code] ....

View 9 Replies View Related

How To Call TRIGGER In VB.net 2005

Sep 26, 2007

i hav written a trigger in SQLEXPRESS DB but i dnt knw how to call in vb.net 2005...

View 2 Replies View Related

How Can I Call A Dll/exe From My Procedure/trigger

Nov 30, 2007

Hi I am trying to run a dll or exe from a procedure or trigger in the database.

I have tried EXEC master ..xp_cmdshell '\xx empdivConsoleApplication1.exe' and
use master exec dbo.StoredProcedure1

If I run the exe from explorer all is working, but from a trigger or procedure in the database nothing happens only executed successfully.

I loaded the assembly and procedure into the master database



Code Block
CREATE PROCEDURE [dbo].[ClassLibrary3] AS EXTERNAL NAME
[ClassLibrary3].[ClassLibrary3.Class1].[StoredProcedure1]





My C# code:


Code Block
public partial class StoredProcedures
{ [Microsoft.SqlServer.Server.SqlProcedure]

public static void StoredProcedure1()
{ //------first a select to get some data String prosjekter = "";
String connString = @"Data Source=serverOFFICESERVERS;Initial Catalog=WSS_Content;Integrated Security=SSPI";
SqlConnection conn = new SqlConnection(connString);
SqlCommand sqlcmd = new SqlCommand("Select nvarchar3 prosjekt from dbo.AllUserData where tp_listId = @listid", conn);
sqlcmd.Parameters.AddWithValue("@listid", "xxx"); try { conn.Open(); SqlDataReader r = sqlcmd.ExecuteReader();
while (r.Read())
{ prosjekter += "" + r["prosjekt"] + "" + "";
}
r.Close(); conn.Close();
} catch (Exception)
{ conn.Close(); }
//-----write some changes back to a program pocketForm pf = new pocketForm();
try {
pf.LoadFromFile("C:/temp/div/xxx.xpf");
string xmlstring = pf.FormXML;
int id, item, items; id = xmlstring.IndexOf("xxxxx");
item = xmlstring.IndexOf("", id);
items = xmlstring.IndexOf("", item);
xmlstring = xmlstring.Remove(item, items - item);
xmlstring = xmlstring.Insert(item, prosjekter);
pf.FormXML = xmlstring;
pf.StatusModifiedLocally = true;
WebService.Login("http://xxxx.no", "xx", string.Empty, string.Empty);
WebService.Save(pf);
} catch (Exception)
{
}

What am I missing here ? Please answer this as I have tried everything with no success. Regards Ivar

View 5 Replies View Related

How To Call A VB Program From A Trigger Of SQL Server

Feb 23, 2004

Hi,

I have a VB program to sit somethere. I like to call that program with passing two parameters from a trigger on the SQL Server. The parameters are the contents of the table which the trigger is created on.

Is there any way to achieve that?

Thanks a lot!

Regards,

Kevin Jin

View 1 Replies View Related

Call Sproc From Trigger Question

Jun 18, 2008

Hi. Apologies if this has come up before, I wonder if someone can help.

I want to call a sproc from a trigger, passing in the value of a field from the updated/inserted/deleted row.

It would be like spUpdateUser @UserID = x

where x is the value from one of the columns of updated row.

What is the syntax for this please? TIA

View 8 Replies View Related

Call Webservice From Trigger/stored Proc

Sep 17, 2004

Is it possible to call an external web service from a SQL Server trigger or stored procedure?

View 6 Replies View Related

Context Of Procedure Call That Results In Trigger

May 8, 2008

If an application makes a connection under a given user, performs the following:
- calls a stored procedure which performs an insert,
- the insert causes a trigger to be fired
- the trigger causes a sql statement to execute against a different
database

Questions:
* Does the user who called the procedure, also need permissions to this 2nd database ?
* What security context does this trigger get executed ?


I have a stored procedure that is being called by my .Net application. The user account that makes the connection has execute permission to the procedure. However, the procedure does an insert which causes a trigger to fire. This trigger does a sql statement against a table in a different database, which the user who is calling the procedure, does not have permissions to access. Im getting an exception when I call the procedure, and it basically says there was a permission error with the user accessing this other database.

View 2 Replies View Related

Multiple Insert Call For A Table Having Insert Trigger

Mar 1, 2004

Hi

I am trying to use multiple insert for a table T1 to add multiple rows.

Ti has trigger for insert to add or update multiple rows in Table T2.

When I provide multiple insert SQL then only first insert works while rest insert statements does not work

Anybody have any idea about why only one insert works for T1

Thanks

View 10 Replies View Related

Call & Exec Batch File From Query Analyzer

Apr 16, 2001

How can I call a batch file from within Query Analyzer, which is the same batch I'm using with isqlw command.

Thanks

View 3 Replies View Related

Modify The RSReportServer.config File With Web Service Call

Jan 11, 2008

Is there a way to modify the RSReportServer.config file with a Web Service call. We want to install an app and have it modify the Renders. We want to remove the Tiff export for example. We also want to add simple headers to Excel. Right now we have to open the file and then make our edits.

View 1 Replies View Related

Call Sql File Within Sql File

Mar 31, 2006

in oracle we run sql files like this

@xxx.sql

what about ms sql

View 4 Replies View Related

OLE DB SOURCE Failure - The Buffer Manager Could Not Get A Temporary File Name. The Call To GetTempFileName Failed.

Mar 14, 2008



Hello,

I am running Data Flow and it fails on the OLE DB Source. Source has 13 fields in the table. One of the field is text (blob, comma delimited string - can be big) which creates a problem. This data flow runs fine with smaller amout of data. In this case Source table has 200,000 records.

The error I am getting is:

Error: 0x80070050 at Data Flow Task - SegStats, DTS.Pipeline: The file exists.
Error: 0x80070050 at Data Flow Task - SegStats, DTS.Pipeline: The file exists.
Error: 0xC0048019 at Data Flow Task - SegStats, DTS.Pipeline: The buffer manager could not get a temporary file name. The call to GetTempFileName failed.
Error: 0xC0048019 at Data Flow Task - SegStats, DTS.Pipeline: The buffer manager could not get a temporary file name. The call to GetTempFileName failed.
Error: 0xC0048013 at Data Flow Task - SegStats, DTS.Pipeline: The buffer manager could not create a temporary file on the path "C:DOCUME~1vitaaLOCALS~1Temp". The path will not be considered for temporary storage again.
Error: 0xC0048013 at Data Flow Task - SegStats, DTS.Pipeline: The buffer manager could not create a temporary file on the path "C:DOCUME~1vitaaLOCALS~1Temp". The path will not be considered for temporary storage again.
Error: 0x80070050 at Data Flow Task - SegStats, DTS.Pipeline: The file exists.
Error: 0xC0048019 at Data Flow Task - SegStats, DTS.Pipeline: The buffer manager could not get a temporary file name. The call to GetTempFileName failed.
Error: 0x80070050 at Data Flow Task - SegStats, DTS.Pipeline: The file exists.
Error: 0xC0048013 at Data Flow Task - SegStats, DTS.Pipeline: The buffer manager could not create a temporary file on the path "C:DOCUME~1vitaaLOCALS~1Temp". The path will not be considered for temporary storage again.
Error: 0xC0048019 at Data Flow Task - SegStats, DTS.Pipeline: The buffer manager could not get a temporary file name. The call to GetTempFileName failed.
Error: 0xC0048013 at Data Flow Task - SegStats, DTS.Pipeline: The buffer manager could not create a temporary file on the path "C:DOCUME~1vitaaLOCALS~1Temp". The path will not be considered for temporary storage again.
Error: 0xC0047070 at Data Flow Task - SegStats, DTS.Pipeline: The buffer manager cannot create a file to spool a long object on the directories named in the BLOBTempStoragePath property. Either an incorrect file name was provided, or there are no permissions.
Error: 0xC0047070 at Data Flow Task - SegStats, DTS.Pipeline: The buffer manager cannot create a file to spool a long object on the directories named in the BLOBTempStoragePath property. Either an incorrect file name was provided, or there are no permissions.
Error: 0x80004005 at Data Flow Task - SegStats, DTS.Pipeline: Unspecified error
Error: 0x80004005 at Data Flow Task - SegStats, DTS.Pipeline: Unspecified error
Error: 0xC0208266 at Data Flow Task - SegStats, DTS.Pipeline: Long data was retrieved for a column but cannot be added to the Data Flow task buffer.
Error: 0xC0208266 at Data Flow Task - SegStats, DTS.Pipeline: Long data was retrieved for a column but cannot be added to the Data Flow task buffer.
Warning: 0x80004005 at Data Flow Task - SegStats, Sort 2 [525]: Unspecified error
Error: 0xC0208265 at Data Flow Task - SegStats, OLE DB Source - LS - Sensor table [1]: Failed to retrieve long data for column "DataPnts".
Error: 0xC0047070 at Data Flow Task - SegStats, DTS.Pipeline: The buffer manager cannot create a file to spool a long object on the directories named in the BLOBTempStoragePath property. Either an incorrect file name was provided, or there are no permissions.
Error: 0x80004005 at Data Flow Task - SegStats, DTS.Pipeline: Unspecified error
Error: 0xC0208266 at Data Flow Task - SegStats, DTS.Pipeline: Long data was retrieved for a column but cannot be added to the Data Flow task buffer.
Warning: 0x80004005 at Data Flow Task - SegStats, Sort 2 [525]: Unspecified error
Error: 0xC0047070 at Data Flow Task - SegStats, DTS.Pipeline: The buffer manager cannot create a file to spool a long object on the directories named in the BLOBTempStoragePath property. Either an incorrect file name was provided, or there are no permissions.
Error: 0xC020901C at Data Flow Task - SegStats, OLE DB Source - LS - Sensor table [1]: There was an error with output column "DataPnts" (27) on output "OLE DB Source Output" (12). The column status returned was: "DBSTATUS_UNAVAILABLE".
Error: 0x80004005 at Data Flow Task - SegStats, DTS.Pipeline: Unspecified error
Error: 0xC0208266 at Data Flow Task - SegStats, DTS.Pipeline: Long data was retrieved for a column but cannot be added to the Data Flow task buffer.
Error: 0xC0209029 at Data Flow Task - SegStats, OLE DB Source - LS - Sensor table [1]: SSIS Error Code DTS_E_INDUCEDTRANSFORMFAILUREONERROR. The "output column "DataPnts" (27)" failed because error code 0xC0209071 occurred, and the error row disposition on "output column "DataPnts" (27)" specifies failure on error. An error occurred on the specified object of the specified component. There may be error messages posted before this with more information about the failure.
Warning: 0x80004005 at Data Flow Task - SegStats, Sort 2 [525]: Unspecified error
Error: 0xC0047038 at Data Flow Task - SegStats, DTS.Pipeline: SSIS Error Code DTS_E_PRIMEOUTPUTFAILED. The PrimeOutput method on component "OLE DB Source - LS - Sensor table" (1) returned error code 0xC0209029. The component returned a failure code when the pipeline engine called PrimeOutput(). The meaning of the failure code is defined by the component, but the error is fatal and the pipeline stopped executing. There may be error messages posted before this with more information about the failure.
Error: 0xC0047070 at Data Flow Task - SegStats, DTS.Pipeline: The buffer manager cannot create a file to spool a long object on the directories named in the BLOBTempStoragePath property. Either an incorrect file name was provided, or there are no permissions.
Error: 0x80004005 at Data Flow Task - SegStats, DTS.Pipeline: Unspecified error
Error: 0xC0208266 at Data Flow Task - SegStats, DTS.Pipeline: Long data was retrieved for a column but cannot be added to the Data Flow task buffer.
Warning: 0x80004005 at Data Flow Task - SegStats, Sort 2 [525]: Unspecified error
Error: 0xC0047021 at Data Flow Task - SegStats, DTS.Pipeline: SSIS Error Code DTS_E_THREADFAILED. Thread "SourceThread0" has exited with error code 0xC0047038. There may be error messages posted before this with more information on why the thread has exited.
Error: 0xC0047070 at Data Flow Task - SegStats, DTS.Pipeline: The buffer manager cannot create a file to spool a long object on the directories named in the BLOBTempStoragePath property. Either an incorrect file name was provided, or there are no permissions.
Error: 0xC0047039 at Data Flow Task - SegStats, DTS.Pipeline: SSIS Error Code DTS_E_THREADCANCELLED. Thread "WorkThread3" received a shutdown signal and is terminating. The user requested a shutdown, or an error in another thread is causing the pipeline to shutdown. There may be error messages posted before this with more information on why the thread was cancelled.
Error: 0xC0047039 at Data Flow Task - SegStats, DTS.Pipeline: SSIS Error Code DTS_E_THREADCANCELLED. Thread "WorkThread4" received a shutdown signal and is terminating. The user requested a shutdown, or an error in another thread is causing the pipeline to shutdown. There may be error messages posted before this with more information on why the thread was cancelled.
Error: 0xC0047039 at Data Flow Task - SegStats, DTS.Pipeline: SSIS Error Code DTS_E_THREADCANCELLED. Thread "WorkThread2" received a shutdown signal and is terminating. The user requested a shutdown, or an error in another thread is causing the pipeline to shutdown. There may be error messages posted before this with more information on why the thread was cancelled.
Error: 0x80004005 at Data Flow Task - SegStats, DTS.Pipeline: Unspecified error
Error: 0xC0208266 at Data Flow Task - SegStats, DTS.Pipeline: Long data was retrieved for a column but cannot be added to the Data Flow task buffer.
Error: 0xC0047021 at Data Flow Task - SegStats, DTS.Pipeline: SSIS Error Code DTS_E_THREADFAILED. Thread "WorkThread4" has exited with error code 0xC0047039. There may be error messages posted before this with more information on why the thread has exited.
Error: 0xC0047021 at Data Flow Task - SegStats, DTS.Pipeline: SSIS Error Code DTS_E_THREADFAILED. Thread "WorkThread2" has exited with error code 0xC0047039. There may be error messages posted before this with more information on why the thread has exited.
Warning: 0x80004005 at Data Flow Task - SegStats, Sort 2 [525]: Unspecified error
Error: 0xC0047021 at Data Flow Task - SegStats, DTS.Pipeline: SSIS Error Code DTS_E_THREADFAILED. Thread "WorkThread3" has exited with error code 0xC0047039. There may be error messages posted before this with more information on why the thread has exited.
Error: 0xC0047070 at Data Flow Task - SegStats, DTS.Pipeline: The buffer manager cannot create a file to spool a long object on the directories named in the BLOBTempStoragePath property. Either an incorrect file name was provided, or there are no permissions.
Error: 0x80004005 at Data Flow Task - SegStats, DTS.Pipeline: Unspecified error
Error: 0xC0208266 at Data Flow Task - SegStats, DTS.Pipeline: Long data was retrieved for a column but cannot be added to the Data Flow task buffer.
Warning: 0x80004005 at Data Flow Task - SegStats, Sort 2 [525]: Unspecified error
Error: 0xC0047070 at Data Flow Task - SegStats, DTS.Pipeline: The buffer manager cannot create a file to spool a long object on the directories named in the BLOBTempStoragePath property. Either an incorrect file name was provided, or there are no permissions.
Error: 0x80004005 at Data Flow Task - SegStats, DTS.Pipeline: Unspecified error
Error: 0xC0208266 at Data Flow Task - SegStats, DTS.Pipeline: Long data was retrieved for a column but cannot be added to the Data Flow task buffer.
Warning: 0x80004005 at Data Flow Task - SegStats, Sort 2 [525]: Unspecified error
Error: 0xC0047070 at Data Flow Task - SegStats, DTS.Pipeline: The buffer manager cannot create a file to spool a long object on the directories named in the BLOBTempStoragePath property. Either an incorrect file name was provided, or there are no permissions.
Error: 0x80004005 at Data Flow Task - SegStats, DTS.Pipeline: Unspecified error
Error: 0xC0208266 at Data Flow Task - SegStats, DTS.Pipeline: Long data was retrieved for a column but cannot be added to the Data Flow task buffer.
Warning: 0x80004005 at Data Flow Task - SegStats, Sort 2 [525]: Unspecified error
Error: 0xC0047070 at Data Flow Task - SegStats, DTS.Pipeline: The buffer manager cannot create a file to spool a long object on the directories named in the BLOBTempStoragePath property. Either an incorrect file name was provided, or there are no permissions.
Error: 0x80004005 at Data Flow Task - SegStats, DTS.Pipeline: Unspecified error
Error: 0xC0208266 at Data Flow Task - SegStats, DTS.Pipeline: Long data was retrieved for a column but cannot be added to the Data Flow task buffer.
Warning: 0x80004005 at Data Flow Task - SegStats, Sort 2 [525]: Unspecified error
Error: 0xC0047070 at Data Flow Task - SegStats, DTS.Pipeline: The buffer manager cannot create a file to spool a long object on the directories named in the BLOBTempStoragePath property. Either an incorrect file name was provided, or there are no permissions.
Error: 0x80004005 at Data Flow Task - SegStats, DTS.Pipeline: Unspecified error
Error: 0xC0208266 at Data Flow Task - SegStats, DTS.Pipeline: Long data was retrieved for a column but cannot be added to the Data Flow task buffer.
Warning: 0x80004005 at Data Flow Task - SegStats, Sort 2 [525]: Unspecified error
Error: 0xC0047070 at Data Flow Task - SegStats, DTS.Pipeline: The buffer manager cannot create a file to spool a long object on the directories named in the BLOBTempStoragePath property. Either an incorrect file name was provided, or there are no permissions.
Error: 0x80004005 at Data Flow Task - SegStats, DTS.Pipeline: Unspecified error
Error: 0xC0208266 at Data Flow Task - SegStats, DTS.Pipeline: Long data was retrieved for a column but cannot be added to the Data Flow task buffer.
Warning: 0x80004005 at Data Flow Task - SegStats, Sort 2 [525]: Unspecified error
Error: 0xC0047070 at Data Flow Task - SegStats, DTS.Pipeline: The buffer manager cannot create a file to spool a long object on the directories named in the BLOBTempStoragePath property. Either an incorrect file name was provided, or there are no permissions.
Error: 0x80004005 at Data Flow Task - SegStats, DTS.Pipeline: Unspecified error
Error: 0xC0208266 at Data Flow Task - SegStats, DTS.Pipeline: Long data was retrieved for a column but cannot be added to the Data Flow task buffer.
Warning: 0x80004005 at Data Flow Task - SegStats, Sort 2 [525]: Unspecified error
Error: 0xC0047070 at Data Flow Task - SegStats, DTS.Pipeline: The buffer manager cannot create a file to spool a long object on the directories named in the BLOBTempStoragePath property. Either an incorrect file name was provided, or there are no permissions.
Error: 0x80004005 at Data Flow Task - SegStats, DTS.Pipeline: Unspecified error
Error: 0xC0208266 at Data Flow Task - SegStats, DTS.Pipeline: Long data was retrieved for a column but cannot be added to the Data Flow task buffer.
Warning: 0x80004005 at Data Flow Task - SegStats, Sort 2 [525]: Unspecified error
Error: 0xC0047039 at Data Flow Task - SegStats, DTS.Pipeline: SSIS Error Code DTS_E_THREADCANCELLED. Thread "WorkThread0" received a shutdown signal and is terminating. The user requested a shutdown, or an error in another thread is causing the pipeline to shutdown. There may be error messages posted before this with more information on why the thread was cancelled.
Error: 0xC0047021 at Data Flow Task - SegStats, DTS.Pipeline: SSIS Error Code DTS_E_THREADFAILED. Thread "WorkThread0" has exited with error code 0xC0047039. There may be error messages posted before this with more information on why the thread has exited.

I also tried to use 3 other temp paths by setting the BLOBTempStoragePath to a semi-colon separated list of paths and it did not help

Any ideas?

Thanks.

View 18 Replies View Related

I Just Want One Entry For Each Call, With SLA Status 'Breach' If Any Of The Stages For The Call Were Out Of SLA.

Mar 19, 2008

Hi,

I am producing a php report using SQL queries to show the SLA status of our calls. Each call has response, fix & completion targets. If any of these targets are breached, the whole SLA status is set as 'Breach'.

The results table should look like the one below:





CallRef.

Description

Severity



ProblemRef

Logged
Date

Call
Status

SLA Status



C0001

Approval for PO€™s not received

2



DGE0014

05-01-06 14:48

Resolved

Breach


C0002

PO€™s not published

2



DGE0014

06-01-06 10:21

Resolved

OK


C0003

Approval for PO€™s not received from Siebel.

2



n/a

05-01-06 14:48

Investigating

OK



















Whereas I can pick the results for the first 6 columns from my Select query, the 'SLA Status' column requires the following calculation:

if (due_date < completed_date)
{ sla_status = 'OK';
}
else sla_status = 'Breach';

The Select statement in my query is looking like this...

Select Distinct CallRef, Description, Severity, ProblemRef, Logdate, Status, Due_date, Completed_date;

The problem is that my query is returning multiple entries for each stage of the call (see below), whereas I just want one entry for each call, with SLA status 'Breach' if any of the stages for the call were out of SLA.






CallRef.

Description

Severity



ProblemRef

Logged
Date

Call
Status

SLA Status



C0001

Approval for PO€™s not received

2



DGE0014

05-01-06 14:48

Resolved

Breach


C0001

Approval for PO€™s not received

2



DGE0014

05-01-06 14:48

Resolved

OK


C0001

Approval for PO€™s not received

2



DGE0014

05-01-06 14:48

Resolved

Breach



















Any help will be much much appreciated, this issue has been bothering me for some time now!!!




View 7 Replies View Related

Trigger To Run An .exe File

Sep 4, 2006

Hi Everyone     I dont have alot of knowledge about how triggers work, but basically I was to run a c# class, or an .exe file from a bin folder as soon as a particular value in a table Database changes. I thought that I  can do that from a trigger, but have no idea how to do that. Can someone please guide me through that process. I have SQL Server 2000 and I am using VS 2003 C# as the language. Thanks-Sarah

View 9 Replies View Related

Trigger To File

Dec 2, 2005

Hi!

I need help with syntax:

CREATE TRIGGER to_file ON TABLE
FOR INSERT
AS
--wher is insert to table -->> row will be direct to file etc.: C:\TEMPlog (txt file???)

Thanks for help with syntax. :) :)

View 1 Replies View Related

Trigger With .txt File Output

Feb 11, 2008

Hello,

This is my first SQL trigger. I trying to create a trigger that will capture update operations on multiple columns within the same table, and output the content of those updates to a .txt file, local on the server.

I have searched this forum, but cannot locate the syntax of this command. Would someone be so kind as to provide an outline of the syntax required to do this? ie;

CREATE TRIGGER [Table_Change] ON [dbo].[table1]
FOR UPDATE
AS
Update (column1, column2, column3)
etc, etc....

Many thanks to all who reply. If I have overlooked this information already posted here, please direct me to the proper location.

Cheers.

View 6 Replies View Related

Using Trigger To Export Xml File

May 4, 2006

Hi all,i am having trouble trying to export this in xml. Basically inside anupdate trigger i need to export in xml or file the qty that has beenchanged. This then gets updated to another system. Is this a good idea? should i be using another table in between in case something happenson the other end?However, I tried something like this and it didn't recognize theselected table inside the bcp:CREATE TRIGGER [TRIGGER NAME] ON [fastpic].[FP_INVTRANS]FOR INSERT, UPDATEASDECLARE @selected varchar (100)IF NOT UPDATE(system_qty)BEGINRETURNENDDECLARE @cmd varchar(200)set @cmd = 'bcp "select system_qty, part_name from selected " queryoutc:parts.xml -S. -Usa -P -c -r -t'exec master ..xp_cmdshell @cmd 'IF someone could help or suggest something else i would appreciate it,than you

View 1 Replies View Related

Create A File Using A SQL DB Trigger

Jul 20, 2005

Is there a way to create a text file (such as a Windows Notepad file)by using a trigger on a table? What I want to do is to send a row ofinformation to a table where the table: tblFileData has only onecolumn: txtOutputI want to use the DB front end (MS Access) to send the text string tothe SQL backend, then have the SQL Server create a file to a path,such as F:/myfiledate.txt that holds the text in txtOutput, then thetrigger deletes the row in tblFileData.Can this be done easily?Any help is appreciated

View 9 Replies View Related

CLR Trigger To Write File.......

Feb 28, 2006

Hello, theres,

I have a request to write to a file whenever new record added to the table.

When records insert row by row, it goes well. but when more than 2 session insert at the same time, sometimes it duplicate some record in the file. I try to add synchonize code ( like lock , Monitor) but it doesn't work. any idea ?

Regards,

Agi

View 3 Replies View Related

Error Message: Error 0x800706BE While Loading Package File D:PackagesToradSales.dtsx. The Remote Procedure Call Failed.

Dec 20, 2006

Hello,

I have a bundling package that runs about 20 other packages. It has been working fine for a while but a couple of days ago it fail with the following message,

Error 0x800706BE while loading package file "D:PackagesToradSales.dtsx". The remote procedure call failed.

I´m running the SSIS packages in an 64-bit environment.

Thankful for help with this!

//Patrick

View 3 Replies View Related

Create Text File And Ftp With Trigger

May 24, 2007

Good day,

I hope someone can help me.

Question 1:
Is it possible to create a text file from a sql server trigger?

Question 2:
Is it possible to ftp a file from a sql server trigger?

Please if anyone can help I would appeciate it.

Thanks

View 10 Replies View Related

Create BAT File And Execute Same In Trigger?

May 9, 2013

I am situation, where we have a table named as Project, columns for the table as follows:

Code:
------------------------------------------
ID | ClientCode | ProjectName
------------------------------------------
1 | AAA | Dubai Airport Phase I
2 | AAA | Dubai Airport Phase II
3 | ARC | Salala
4 | MIZ | UMBC Building
------------------------------------------

Now my task was, whenever a project name and other details being created, then a Folder will be created in a server itself in the path E:ProjectFolder in following way:

E:ProjectFolderAAAAAA1
E:ProjectFolderAAAAAA2
E:ProjectFolderARCARC3
E:ProjectFolderMIZMIZ4

You can see here Folder and sub-folder is being created with that following project - client code & ID

I used following trigger to do the same:

Code:
CREATE TRIGGER [dbo].[CreateFolderName]
ON [dbo].[Project]
after INSERT
AS
SET NOCOUNT ON
BEGIN
declare @chkdirectory as nvarchar(4000), @folderName varchar(100), @mainfolderName varchar(100)
declare @folder_exists as int
SET @mainfolderName = (SELECT ClientCode AS Project FROM INSERTED)
SET @folderName = (SELECT (ClientCode + cast(ID as varchar(10))) AS Project FROM INSERTED)
set @chkdirectory = 'E:ProjectFolder' + @mainfolderName + '' + @folderName

[code].....

This worked like a charm, now my next task is using same trigger, I have to create a BAT file inside that SubFolder - T-SQL for creation of BAT File as follows:

Code:
DECLARE @FileName varchar(50),
@bcpCommand varchar(2000)
SET @FileName = REPLACE('E:ProjectFolder[red](select ClientCode from INSERTED)[/red][red](select ClientCode + cast(ID as varchar(10)) from INSERTED)[/red]xcopy_'+ (SELECT cast(ID as varchar(10)) FROM INSERTED) +'.bat','/','-')
SET @bcpCommand = 'bcp "[red]SELECT 'xcopy "E:ProjectFolder' + clientCode + '" "10.0.0.35ProjectFolder" /T /E /I' FROM INSERTED[/red]" queryout "'
SET @bcpCommand = @bcpCommand + @FileName + '" -U SQLServerUsername -P SQLServerPassword -c'
EXEC master..xp_cmdshell @bcpCommand

Here I am not understanding how to insert the above T-SQL in the Trigger as well as the above T-SQL is not right, what's wrong in this?

Last query that will be included in the trigger is to execute the newly created bat file.

View 1 Replies View Related

Bcp And Trigger: Missing Data In Bcp Out File

Jan 31, 2007

I have made trigger on table 'FER' that would be fired if data isinserted, updated to the table. And also, I made batch file using bcpto extract the newly updated / inserted records.But I got missing data in bcp out file like this:Missing 1200 records, blocked at:/*777946 296188 2007-01-29 21:25:45.063778145 296494 2007-01-29 21:25:47.063*/1. trigger.sqlCREATE TABLE [FERUpdate] ([id] [int] NOT NULL ,[fid] [int] NOT NULL ,[sid] [int] NOT NULL ,[UpdatePass] [int] NULL) ON [PRIMARY]GOcreate trigger trgFERUpdate on FER For Insert,Update asinsert into FERUpdate(id,fid,sid) select ins.id, ins.fid,ins.sid frominserted ins2. bcp.bat----isql -U <user-P <pw-S server -Q "update AA..FERUpdate setUpdatePass=1 where UpdatePass is null"bcp "select a.* from AA..FER a, AA..FERUpdate b where a.fid=b.fid anda.sid=b.sid and b.fid<>-1 and b.sid<>-1 and b.updatepass=1" queryout%TFN_NOW%.wrk -U <user-P <pw-S server -f FER.fmtisql -U <user-P <pw-S server -Q "delete from AA..FERUpdate whereUpdatePass=1"-----I have been struggling with this for these two days. Your any helpsare appreciated, Please help me out!! Thanks!!!

View 2 Replies View Related

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 thistable doesn't work ?I put my code below.Best regardsThank'sDavidXml 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;datasource=*****;database=*****;uid=*****;pwd=*****"objBL.ErrorLogFile = "C:Temperror.xml"objBL.SchemaGen = TrueobjBL.CheckConstraints = TrueobjBL.KeepIdentity = FalseobjBL.BulkLoad = trueobjBL.Execute "C:Temp9219142_MAPPING.xsd", "C:Temp9219142.xml"Set objBL = NothingTrigger source code :CREATE TRIGGER [dbo].[trg_ac_export_and_path] ONdbo.ac_export_and_pathFOR INSERTASDECLARE @id AS varchar(50)SELECT @id = 'A'+convert(varchar, [id]) FROM insertedINSERT INTO ac_path([id], [path]) SELECT @id, path FROM insertedEND

View 4 Replies View Related

Error Msg 6522, Level 16, State 1 Receives When Call The Assembly From Store Procedure To Create A Text File And To Write Text

Jun 21, 2006

Hi,
I want to create a text file and write to text it by calling its assembly from Stored Procedure. Full Detail is given below

I write a code in class to create a text file and write text in it.
1) I creat a class in Visual Basic.Net 2005, whose code is given below:
Imports System
Imports System.IO
Imports Microsoft.VisualBasic
Imports System.Diagnostics
Public Class WLog
Public Shared Sub LogToTextFile(ByVal LogName As String, ByVal newMessage As String)
Dim w As StreamWriter = File.AppendText(LogName)
LogIt(newMessage, w)
w.Close()
End Sub
Public Shared Sub LogIt(ByVal logMessage As String, ByVal wr As StreamWriter)
wr.Write(ControlChars.CrLf & "Log Entry:")
wr.WriteLine("(0) {1}", DateTime.Now.ToLongTimeString(), DateTime.Now.ToLongDateString())
wr.WriteLine(" :")
wr.WriteLine(" :{0}", logMessage)
wr.WriteLine("---------------------------")
wr.Flush()
End Sub
Public Shared Sub LotToEventLog(ByVal errorMessage As String)
Dim log As System.Diagnostics.EventLog = New System.Diagnostics.EventLog
log.Source = "My Application"
log.WriteEntry(errorMessage)
End Sub
End Class

2) Make & register its assembly, in SQL Server 2005.
3)Create Stored Procedure as given below:

CREATE PROCEDURE dbo.SP_LogTextFile
(
@LogName nvarchar(255), @NewMessage nvarchar(255)
)
AS EXTERNAL NAME
[asmLog].[WriteLog.WLog].[LogToTextFile]

4) When i execute this stored procedure as
Execute SP_LogTextFile 'C:Test.txt','Message1'

5) Then i got the following error
Msg 6522, Level 16, State 1, Procedure SP_LogTextFile, Line 0
A .NET Framework error occurred during execution of user defined routine or aggregate 'SP_LogTextFile':
System.UnauthorizedAccessException: Access to the path 'C:Test.txt' is denied.
System.UnauthorizedAccessException:
at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy)
at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, ileOptions options)
at System.IO.StreamWriter.CreateFile(String path, Boolean append)
at System.IO.StreamWriter..ctor(String path, Boolean append, Encoding encoding, Int32 bufferSize)
at System.IO.StreamWriter..ctor(String path, Boolean append)
at System.IO.File.AppendText(String path)
at WriteLog.WLog.LogToTextFile(String LogName, String newMessage)

View 13 Replies View Related

Stored Procedure - Create Trigger File In Particular Directory

Oct 26, 2012

I created stored procedure to create trigger file in a particular directory using xp_cmdshell.

I am calling the procedure from windows batch script as follows

@@set osq200=osql /a 4096 /b /E /e /d %dbn% /m-1 /r 0 /S %dbs% /Q "exec SP_Create_TriggerFile %2,%1 "
@%osq200% >>%3rec.txt 2>%3rec_err.txt
@set dberr=%errorlevel%
@if %dberr% GTR 0 goto createDATriggerFileErr >>%3rec.txt

If the directory doesn't exist, its throwing error "The system cannot find the path specified" , but the %errorlevel% still showing as 0..

View 1 Replies View Related

Integration Services :: Trigger SSIS Package Whenever New CSV File Gets Added To Shared Location

Jul 10, 2015

I have an ssis package that moves data from a new csv file in a share location to sql server database table. However I need to get this agent job triggered whenever a new csv file gets added to the shared location.

What is a best strategy to do this keeping in mind that while package is running and two new csv files come in and package shd copy data from both the files.

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







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