Multiple Connections In Managed Trigger
Apr 13, 2006
Hi All,
I am trying to open multiple connections in a Managed Trigger but encoutering an error as :
System.Data.SqlClient.SqlException: Transaction context in use by another session.
Below is the sample code:
public partial class Triggers
{
[Microsoft.SqlServer.Server.SqlTrigger (Name="TrgInsertContract", Target="Contracts", Event="FOR INSERT")]
public static void TrgInsertContract()
{
SqlTriggerContext triggContext = SqlContext.TriggerContext;
SqlConnection connection = new SqlConnection("context connection = true");
connection.Open();
SqlCommand command = connection.CreateCommand();
command.CommandText = "SELECT * from " + "inserted WHERE Active=1";
SqlDataReader reader;
reader = command.ExecuteReader(CommandBehavior.CloseConnection);
connection.Close();
SqlConnection connection1 = new SqlConnection("Initial Catalog=TestDB;Data Source=SHAIKDEV;User ID=sa;password=****");
connection1.Open();
}
Any help please ?????
Thanks...
View 5 Replies
ADVERTISEMENT
May 23, 2007
Hello
Is there nay way that it is possible to connect to another database within a trigger€¦
My scenario is that an update in a table in database X triggers several updates in a table in Database Y. The databases are on the same SQL Server
Thanks for any ideas, solutions or hints you can give me..!!!
View 5 Replies
View Related
Mar 12, 2007
SQL Server 2005 gives you a possibility to create managed triggers. In a managed trigger I can create a new thread and process trigger event in various ways. My question is that are there any reasons why I should NOT start new threads in database triggers? The following code shows how I could create new threads. Do you see that this could cause any errors or problems in SQL Server functionality? My goal is to minimize the trigger effects in a database overall performance.
'This handles database updates of AdventureWorks Person.Contact table.
<Microsoft.SqlServer.Server.SqlTrigger(Name:="UpdateContact_Trigger", Target:="Person.Contact", Event:="FOR UPDATE")> _
Public Shared Sub UpdateContact_Trigger()
'Notify:
SqlContext.Pipe.Send("Trigger FIRED")
Dim triggContext As SqlTriggerContext = SqlContext.TriggerContext()
'Ensure that it was update:
If triggContext.TriggerAction = TriggerAction.Update Then
'Open a connection:
Using conn As New SqlConnection("context connection=true")
conn.Open()
'Fetch some information about the update:
Using sqlComm As New SqlCommand
sqlComm.Connection = conn
sqlComm.CommandText = "SELECT ContactID, FirstName, LastName from INSERTED"
Using rdr As SqlDataReader = sqlComm.ExecuteReader
If rdr.Read Then
'Process the data in a separate thread. The thread could send a message to MSMQ about the change
'or process if differently. The purpose of using separate thread is avoid performance hit
'in the application / database operation.
Dim oData As New TriggerData("update", rdr.GetInt32(0).ToString, "contact")
Dim trd As New Threading.Thread(New Threading.ThreadStart(AddressOf oData.ProcessEvent))
trd.IsBackground = True
trd.Start()
End If
End Using
End Using
End Using
End If
End Sub
View 2 Replies
View Related
Aug 24, 2007
Hi there,
Values in my database need to updated periodically. The code, upon starting the application, queries the database and stores the values in the Application collection. This is to avoid making a database call everytime the values are needed (increases performance). The drawback is that changes to the database values are not updated in the code.
How can I create a database trigger that will update the C# Application colllection whenever a table value is updated?
View 2 Replies
View Related
Aug 12, 2015
I cannot get a consistent answer as to how many domain accounts would be suggested in a SQL Server 2014 installation. Previously the recommendation was a separate account for each service to provide isolation and minimum permissions for each account. It seems from what I've read that a single domain account would have something added to make it unique from SQL Server's perspective. Several still advocate multiple accounts. I don't know if they are doing so because that's the way it's always been done or if there is still some compelling reason to do so. I don't want to create unnecessary accounts simply because something is "ideal."
View 8 Replies
View Related
Feb 19, 2004
Hi, I have a VB application running on SQL Enterprise Edition. Physically there are only 20 users loging in to the software at one time. However i can see more that 12 SPIDs for each user. The developers have been opening a new connection for each form in the application i guess. Is it normal or is there any specific requirement that foces them to do so? Shall i need to change the default WORKER-THREADS option on the server for peformance? Suggestions please!!!
Regards.
View 7 Replies
View Related
Nov 3, 2005
Here's what I'm trying to accomplish:
View 5 Replies
View Related
Feb 21, 2007
I have a SQLExpress Database that I can connect to from a C# application and seperately from an application via 'OBDC' with NO problems. Both applications are running on the Local PC running XPpro.
However, I cannot connect to the same database from both applications at the same time!
Is there a way around this ?, is it a restriction of the Express version ?
View 3 Replies
View Related
Jan 3, 2008
I am using ODBC to connect to SQL Server. The documentation says that ODBC transactions are managed on the connection level and cannot span connections.
Does this mean that two instances of my code using transactions (each with its own process and a single connection) in the same machine accessing the same database will not play nice together (violate transaction rules)?
Thanks
View 3 Replies
View Related
Feb 4, 2015
If I have 100 ODBC clients all submitting the following SQL at the same time how do I know that the SQL inside the conditional only gets executed once. It appear SQL Server is preventing it from happening but was curious how. Or do I need to add something to prevent it from happening.
IF NOT EXISTS (SELECT name FROM sysobjects WHERE type='U' AND name = 'mytable)
BEGIN
CREATE table mytable (task int NOT NULL, first_name varchar(128), last_name varchar(128))
END
View 1 Replies
View Related
May 3, 2008
basically, is it inefficient to open and close a data connection everytime data needs to be retrieved or is there a way for a user to use the same conenction over multiple pages orfor multiple users to share one global data connection I just wanted to know this before I built a site where data could be constantly being pulled or put into the database.It would be easier to just keep opening and closing the connection since it just means pasting in the small chunk of code I use to do that where I need it. I hear speak of connections sometimes not closing etc and wonder if that is an issue then if you are opening and closing too many of them. I am using SqlConnection SqlCommand and SqlDatareader , my code works, just wondering if my approach lacked scalability before I find out too late and have to rewrite everything . Jim
View 11 Replies
View Related
Apr 8, 2007
Hello
Is it possible to create a trigger with multiple actions?
I would like to create a trigger with INSERT, DELETE, UPDATE funtions but I have not been above to find a clear syntax example
Below I have created a statement of my trigger. Could somebody please confirm if the syntac in this multiple action trigger is ok.multple actions on a single trigger
Is this syntax correct?
CREATE TRIGGER [dbo].[trig_AddDomCatA] ON DomainNames For INSERT, DELETE, UPDATE
AS
INSERT INTO Domain_CatA (DomainName)SELECT DomainName FROM INSERTED
ASDELETE FROM Domain_CatA (DomainName)SELECT DomainName FROM DELETED
ASUPDATE INTO Domain_CatA (DomainName)SELECT DomainName FROM UPDATED
Thanks
Lynn
View 7 Replies
View Related
Oct 30, 2003
I have a messy design that I can't change but need to keep in synch. I have a master table where a person's info is entered into. Upon that entry I have to take that info (name, bdate,ssn,location) and populate it to 4 separate tables in 4 separate databases, all of which have their own id field which has to be incremented (no none of them are identity columns). At the end of the process I have to update the master record with the id fields of all the other four tables. I was going to do this with an insert trigger. As far as protecting the id's across all four databases, I was going to use a begin trans and get the next id field for all four databases and then apply the logic to add the records. Does this seem a safe approach, or am I missing something? Do I need to do a begin tran for each database separately?
THanks
View 1 Replies
View Related
Aug 17, 2007
I have a question regarding Triggers.
Lets say I want to create a trigger for Insert, Update and Delete action. For each action I do different things.
Now I can create a single trigger for Insert, delete and update, and using counts for inserted and deleted table, take the action appropriately.
Or I can create three different triggers each for Insrt, update and delete.
Which option is better for performance?
Thanks
View 2 Replies
View Related
Jun 1, 2006
Hi i've searched a lot with no results, im trying to do a trigger, this is the scenario
Got 3 tables, Product, Lines, Sublines
If Update Multiple sublines it should be updated to the products table, but i cant because the inserted table has multiple rows, the only way to do this is using cursors???
(Note, i cant do this using cascade because there are others, if i include this get a circular problem so i have to solve this other way)
View 1 Replies
View Related
Feb 10, 2014
I have a requirement that if in a table update happened based on 1st condition then it should insert in one way and if update happened on second condition the insert statement will differ. That is it should insert the deleted records i.e., previous records existed in a table.The syntax is like
CREATE TRIGGER [dbo].[tr_a] on [dbo].[A]
AFTER UPDATE
AS
BEGIN TRY
IF NOT EXISTS
[code]....
I m getting some syntactical errors.
View 6 Replies
View Related
Apr 15, 2014
I have the following trigger that updates a couple test fields to null when they are 1/1/1900, works great on inserts, and one line updates:
CREATE TRIGGER UpdateDate
ON test
AFTER INSERT, UPDATE
AS
UPDATE Test
SET
[CheckDate] = CASE WHEN [CheckDate] = '19000101' THEN NULL ELSE [CheckDate] END,
[CheckDate2] = CASE WHEN [CheckDate2] = '19000101' THEN NULL ELSE [CheckDate2] END
where AutoID = (select AutoID from inserted)
However, when trying to do a multi line update statement, I get the following error:
Msg 512, Level 16, State 1, Procedure UpdateDate, Line 7
Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.The statement has been terminated
How can I get around this?
View 5 Replies
View Related
Feb 15, 2008
Hi,
I have a SQL Agent Job that selects records that are of a particular age (from Table1) and inserts them into another table (Table 2) - multiple records get inserted as a single INSERT step. On Table 2 I then have a trigger set FOR INSERT which I was hoping would send an email using the fields copied from the batch job, one of which being an email address.
The trigger is: -
Code Snippet
CREATE TRIGGER trgSendMail ON Table2 FOR INSERT AS
DECLARE @myEmail VarChar(50)
SELECT @myEmail = strEmail FROM Inserted
EXEC sp_send_dbmail
@Profile_Name = '{MailProfile}',
@Recipients = @myEmail,
@Subject = '{MailTitle}',
@Body = '{MailBody}'
Thing is, the agent works fine but the trigger only sends an email to the first row inserted.
Any ideas on how to get around this so that if the batch job inserts 10 rows into Table2 then 10 emails are sent out?
Shaun.
View 6 Replies
View Related
May 1, 2001
I have a table which when certain columns are updated, need a trigger to fire to update a next schedule date in that same table for that record. I can write the trigger, but my question for performance and efficiency is which approach would be better. Separate triggers fo the 8 columns, or a large trigger with an If to check if these columns are updated.
Thanks
View 1 Replies
View Related
Apr 21, 2004
Hey, I have couple of triggers to one of the tables. It is failing if I update multiple records at the same time from the stored procedure.
UPDATE
table1
SET
col1 = 0
WHERE col2 between 10 and 20
Error I am getting is :
Server: Msg 512, Level 16, State 1, Procedure t_thickupdate, Line 12
Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.
The statement has been terminated.
What is the best possible way to make it work? Thank you.
View 7 Replies
View Related
Jun 11, 2008
DESCRIPTION: I have an FTP server set up to log via ODBC into a table FTPLog. The trigger on table FTPLog fires when new files are received to process and load the file via a stored procedure.
CREATE TRIGGER tr_new_file ON FTPLog
AFTER INSERT
AS
SET NOCOUNT ON
DECLARE @filename varchar(50), @logtime datetime
DECLARE c1 CURSOR
FOR SELECT filename, logtime
FROM inserted
OPEN c1
FETCH NEXT FROM c1
INTO @filename, @logtime
WHILE @@fetch_status = 0
BEGIN
EXEC sp1 @filename, @logtime
FETCH NEXT FROM c_inserted
INTO @filename, @logtime
END
CLOSE c1
DEALLOCATE c1
END
PROBLEM: There are multiple problems with this setup. The first problem is that when the stored procedure gets executed it takes a long time to process the file and the FTP server never returned a completion code to the ftp client and ended with a connection time out from the client. My users keep asking if the FTP failed but it didnt fail. The server returned a completion code too late.
PROBLEM2: When multiple files are ftp to the server on the same session, only the first one gets process. Even though my code loops through all the records because the processing takes a long time the second one never gets executed. If I replace the EXEC sp1 statement with a PRINT statement then it's working fine.
SOLUTIONS and SUGGESTIONS highly appreciated.
View 13 Replies
View Related
Jul 23, 2005
I have written a trigger that's supposed to go out and deletecorresponding records from multiple tables once I delete a specificrecord from a table called tblAdmissions.This does not work and I'm not sure why...Here's the code that's supposed to run, let's say, if a user (via a VB6.0 interface) decides to delete a record. If the record in thetblAdmissions table has the primary key (AdmissionID) of "123", thenthe code below is supposed to search other tables that have relatedinformation in them and also have an AdmissionID of "123" and deletethat information as well.Any ideas? Here's the code:CREATE TRIGGER tr_DeleteAdmissionRelatedInfo-- and here is the table nameON tblAdmissions-- the operation type goes hereFOR DELETEAS-- I just need one variable this timeDECLARE @AdmissionID int-- Now I'll make use of the deleted virtual tableSELECT @AdmissionID = (SELECT @AdmissionID FROM Deleted)-- And now I'll use that value to delete the data in-- the tblASIFollowUp TableDELETE FROM tblASIFollowUpWHERE AdmissionID = @AdmissionID-- And now I'll use that value to delete the data in-- the tblProgramDischarge TableDELETE FROM tblProgramDischargeWHERE AdmissionID = @AdmissionID-- And now I'll use that value to delete the data in-- the tblRoomAssignment TableDELETE FROM tblRoomAssignmentWHERE AdmissionID = @AdmissionID-- And now I'll use that value to delete the data in-- the tblTOADS TableDELETE FROM tblTOADSWHERE AdmissionID = @AdmissionID-- And now I'll use that value to delete the data in-- the tblUnitedWaySurvey TableDELETE FROM tblUnitedWaySurveyWHERE AdmissionID = @AdmissionID-- And now I'll use that value to delete the data in-- the tblWFGMSurvey TableDELETE FROM tblWFGMSurveyWHERE AdmissionID = @AdmissionID
View 4 Replies
View Related
Apr 23, 2015
we have a table in database , which has multiple triggers defined by Vendor. I have created our own custom trigger on this table also , which fires last. Goal of this custom trigger is to send an email, when ever update happens on table. But somehow trigger is firing multiple times for same update, so it is sending multiple email for same update also
View 7 Replies
View Related
Dec 28, 2007
I was able to catch one update but not multiple updates or batch updates done to the table. I know the updated records are residing in inserted and deleted tables. Without using cursors, how can i read and compare all the rows in these two tables?
Following is the table structure:
Customer_Master(custmastercode, customer_company_name,updated_by)
Following is the trigger:
ALTER TRIGGER [TR_UPDATE_CUST]
ON [dbo].[CUSTOMER_MASTER]
AFTER UPDATE
AS
BEGIN
SET NOCOUNT ON;
IF EXISTS (SELECT * FROM inserted)
BEGIN
declare @custcode int
Declare @message varchar(5000)
Declare @custommessage varchar(2000)
Declare @CUSTMASTERCODE int
Declare @CUSTOMER_COMPANY_NAME varchar(50)
Set @message = 'Changes in customer account number ' + Cast ((@custcode) as varchar(10)) + ': '
select @custcode = [CUSTMASTERCODE],@UPDATED_BY = [UPDATED_BY] from inserted
Set @message = 'Changes in customer account number ' + Cast ((@custcode) as varchar(10)) + ': '
IF(update([CUSTOMER_COMPANY_NAME]))
Begin
select @UCUSTOMER_COMPANY_NAME = [CUSTOMER_COMPANY_NAME] from deleted
select @CUSTOMER_COMPANY_NAME = [CUSTOMER_COMPANY_NAME] from inserted
Set @custommessage = 'Customer company name changed from ' + @UCUSTOMER_COMPANY_NAME + ' to ' + @CUSTOMER_COMPANY_NAME + '.'
Set @message = @message + @custommessage
End
Set @message = @message + ' Updated by ' + @UPDATED_BY + ' at ' + CAST(getdate() AS VARCHAR(20))+ '.'
INSERT INTO [CHANGE_HISTORY]
([CUSTMASTERCODE]
,[CHANGE_DETAILS])
VALUES (@custcode, @message)
END
END
View 7 Replies
View Related
Jul 17, 2007
Hello,
Anyone know how to create an update trigger where the primary key isn't fixed.
If the primary key change how can I tie together the Deleted and Inserted tables if more than one row is updated?
/Patrik
View 9 Replies
View Related
Jan 17, 2012
Multiple rows to insert:
---------------------
insert into Customer(CustomerId,Name,Value)
select CustomerId,Name,Value
from CustomerTemp
Trigger in Customer table that invoke a function:
alter TRIGGER [dbo].[Calculation] ON [dbo].[Customer]
AFTER INSERT
AS
update Customer
set Percentage = dbo.GetPercentage((select Value from inserted))
where CustomerId = (select CustomerId from inserted)
I'm getting the error for the multiple row.Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.Is there a way to let me insert multiple rows, using the trigger that invoke a function ?
View 1 Replies
View Related
Sep 6, 2007
My goal is to create a trigger to automatically set the value for a status id on a table based on set criteria. Depending on the values of other fields will determine the value that the status id field is assigned. So far, I have written the trigger to update the status id field and I go through a seperate Update statement for each status id value. The problem is that I can't get this to work at the record level. The problem that I am getting is that if I have 50 records in TABLE1 and at least one of them satisfies the where clause of the update statement, all of the records get updated. So, using these two update statements, all of my records end up with a status value of '24' because that was the last update statement run in the trigger. Here is the code I have so far:
CREATE TRIGGER dbo.JulieTrigger1
ON dbo.Table1
AFTER INSERT,UPDATE
AS
BEGIN
BEGIN TRY
/*Update Table1.Status to POTENTIAL (id 23) status */
UPDATE TABLE1
SET status_id = 23
WHERE EXISTS (SELECT *
FROM TABLE1 a INNER JOIN TABLE2 b
ON b.order_id = a.order_id
WHERE a.start_dt IS NULL
AND b.current_status_ind = 1
AND b.lead_status_id NOT IN (15,16)
AND a.order_id = TABLE1.order_id)
/*Update Table1.Status to ACTIVE (id 24) status */
UPDATE TABLE1
SET status_id = 24
WHERE EXISTS (SELECT *
FROM TABLE1 a
WHERE fill_ind = 1
AND (end_dt IS NULL OR end_dt > getdate() )
AND a.job_order_id = TABLE1.job_order_id)
END TRY
BEGIN CATCH
DECLARE @ErrorMessage NVARCHAR(4000);
DECLARE @ErrorSeverity INT;
DECLARE @ErrorState INT;
SELECT
@ErrorMessage = ERROR_MESSAGE(),
@ErrorSeverity = ERROR_SEVERITY(),
@ErrorState = ERROR_STATE()
IF @@TRANCOUNT > 0
ROLLBACK TRAN
-- Return the error to the calling object
RAISERROR (@ErrorMessage, -- Message text.
@ErrorSeverity, -- Severity.
@ErrorState -- State.
)
END CATCH
SET NOCOUNT ON;
END
GO
Thanks in advance for any help!
-Julie
View 1 Replies
View Related
Aug 6, 2014
I create a Trigger that allows to create news row on other table.
ALTER TRIGGER [dbo].[TI_Creation_Contact_dansSLX]
ON [dbo].[_IMPORT_FILES_CONTACTS]
AFTER INSERT
AS
[code]...
But if I create an INSERT with 50 rows.. My table CONTACT and ADDRESS possess just one line.I try to create a Cursor.. but I had 50 lines with an AdressID and a ContactID differently, but an Account and an AccountId egual on my CONTACT table :
C001 - AD001 - AC001 - ACCOUNT 001
C002 - AD002 - AC001 - ACCOUNT 001
C003 - AD003 - AC001 - ACCOUNT 001
C004 - AD004 - AC001 - ACCOUNT 001
C005 - AD005 - AC001 - ACCOUNT 001
I search a means to have 50 lines differently on my CONTACT table.
C001 - AD001 - AC001 - ACCOUNT 001
C002 - AD002 - AC002 - ACCOUNT 002
C003 - AD003 - AC003 - ACCOUNT 003
C004 - AD004 - AC004 - ACCOUNT 004
C005 - AD005 - AC005 - ACCOUNT 005
View 9 Replies
View Related
Jan 15, 2015
I have a After insert, update trigger. When I update multiple records with unique constraints column in it update fails. But if this a single record update it works.
Could like to know the reason.
View 9 Replies
View Related
Jul 30, 2007
Assuming I should be using values from temp inserted to insure correct record...
Need help coding IF...THEN INSERT statements in following After TRIGGER:
Create TRIGGER trg_insertItemRows
ON dbo.a_form
AFTER INSERT
AS
SET NOCOUNT ON
-- Checkbox Driven:
IF a_form.missingCheckbox = -1 THEN
Insert into b_items (form_ID, parent_ID, ItemTitle)
Values (Select Distinct i.form_ID,i.parent_ID from inserted i)', '+ 'User checked Missing Data')
-- Textbox Driven:
IF a_form.incorrectTxtbox <> 'na' THEN
Insert into b_items (form_ID, parent_ID, ItemTitle)
Values (Select Distinct i.form_ID,i.parent_ID from inserted i)', '+ Correction: Replace '+ incorrectTxtbox + ' with '+replaceWithTxtbox)
Sample code below:
-- Source table the Trigger acts on
Create Table a_form (
form_ID int Not Null,
parent_ID int,
missingCheckbox bit,
missingNote varchar(100),
incorrectTxtbox varchar(50),
replaceWithTxtbox varchar(50)
)
--Target table Trigger inserts into
Create Table b_items (
items_ID int Not Null,
form_ID int Not Null,
parent_ID int,
ItemTitle varchar(150)
)
View 5 Replies
View Related
Apr 11, 2007
Can anyone explain to me why I would choose one over the other? Please provide some simple examples of when I would choose each. Thanks!
View 4 Replies
View Related
Mar 21, 2006
Hello people :-)I'm doing some development work with Visual Studio 2005 and SQLServer 2000. My SQL DB is running on a Windows 2000 Server box in the office, and I'm doing the development on my XPPro workstation. Now I've been trying to connect to the Win2000 box though VS and although I can see the server and the DB when I hit ok I get this error"The SQL server specified by these connection propertise does not support managed objects"What the heck does that mean?any help would be great :-)
View 1 Replies
View Related
Jun 18, 2014
I have two tables called ECASE and PROJECT
In the ECASE table there is trigger to get the max value of case_id column in ecase based on project and increment one to that case_id value and insert into ecase table .
When we insert a new record to the ECASE table this trigger calls and insert the case_id column value.
When i run with multiple threads , the transaction is rolled back because of trigger . The reason is , on the project table the lock is happening while getting the max value of case_id column based on project.
I need to prevent the deadlock .
View 3 Replies
View Related