I have SQL Server 2000, and our web application is in WebObjects.
I built a trigger on a table that indicates if certain fields in a record have been changed since the last time a report was run from the application.
This trigger runs fine through the Query Analyzer, and runs fine with a direct input through enterprise manager. However, when the WebObjects application tries to update the table, and error is thrown.
Is anyone familiar with a reason why an application would throw an error on an update, when the DB tools do not? If we disable the trigger, the application has no problem updating the table.
Here is the relevant portion of the trigger:
create trigger t_press_run_change
on dbo.press_run_line_item
for insert, update, delete
as
updatepress_run_line_item
setis_changed = 1
from deleted d
join press_run_line_item p on p.press_run_line_item_id = d.press_run_line_item_id
where(p.is_changed = 0 or p.is_changed is null)
AND ((isNull(p.print_quantity,0) <> isNull(d.print_quantity,0))
OR (isNull(p.spoilage_pct,0) <> isNull(d.spoilage_pct,0))
OR(isNull(p.ad_dimension_id,0) <> isNull(d.ad_dimension_id,0))
OR(isNull(p.quarter_fold_id,0) <> isNull(d.quarter_fold_id,0))
OR(isNull(p.max_qty_per_shipment,'') <> isNULL(d.max_qty_per_shipment,''))
OR(isNull(p.packaging_max_height,'') <> isNull(d.packaging_max_height,''))
OR(isNull(p.packaging_max_weight,'') <> isNull(d.packaging_max_weight,''))
OR(isNull(p.packaging_skids,'') <> isNull(d.packaging_skids,''))
OR(isNull(p.packaging_turns,'') <> isNull(d.packaging_turns,''))
OR(isNull(p.packaging_cartons,'') <> isNull(d.packaging_cartons,''))
OR(isNull(p.preprint_delivery_time,'') <> isNull(d.preprint_delivery_time,''))
OR(isNull(p.contact_id,0)<> isNull(d.contact_id,0))
OR(isNull(p.address_company,'')<>isNull(d.address_company,''))
OR(isNull(p.address1,'')<>IsNull(d.address1,''))
OR(isNull(p.address2,'')<>IsNull(d.address2,''))
OR(isNull(p.address_city,'')<>IsNull(d.address_city,''))
OR(isNull(p.address_state,'')<>IsNull(d.address_state,''))
OR(IsNull(p.address_zip,'')<>IsNull(d.address_zip,''))
OR(isNull(p.address_Country_id,'')<>IsNull(d.address_country_id,''))
OR(isNull(p.client_printer_id,'')<>IsNull(d.client_printer_id,'')))
I'm new to SQL and am having some trouble figuring out Triggers. We use Microsoft Dynamics SL (formerly Solomon) for our accounting. We have a table that only has data in it while we're processing checks called PRCHECKTRAN. We'd like to build a report that uses the information in this table but it's only available until we "keep" the checks that we're printing. This creates an added step because we have to stop our Payroll process to go out and print the reports. It's been suggested to use a trigger to make a copy of the records in the PRCHECKTRAN table so we've got them after the checks are "kept." We're wanting something that's done behind the scenes so the user can continue to do things the way they always have while giving us access to the data past the payroll period.
Basically as soon as we calculate checks, PRCHECKTRAN is populated. Once the checks are accepted as good, PRCHECKTRAN is cleaned out. I think I need an update or insert trigger that copies all records over to another table that we'll create called something like PRCHECKTRAN_HOLD. I'm just not familiar enough with SQL to write it. Any direction you can provide would be greatly appreciated. Thanks.
I have a very complex Stored Procedure called by a Job that is Scheduled to run every night. It's execution takes sometimes 1 or 2 hours and sometimes 7 hours or more.
So, if it is running for more than 4 hours I stop the Job and I run the procedure from a Query Window and it never takes more than 2 hours.
Can anyone help me identify the problem ? I want to run from the Job and not to worry about it.
Some more information: - It is SQL 2000 Enterprise with SP4 in a Cluster (It happens the same way in any node). - The SQL Server and SQL Agent services run using a Domain Account that have full Administrative access. - When I connect to a Query Window I also use a Windows Account.
- There is no locks or process bloking or being blocked while the job is running. - Using the Task Manager the processor activity is ok, no more than 30 % in any processor.
I am trying to run DTS package (stored on SQL Server) using Visual basic but i am getting the following error
Runtime error '-2147217843 (80040e4d)'
Login failed for 'MyUserID'
************************************* i used the following code in VB program
Sub Command1_Click() Dim dtsp As New DTS.Package dtsp.LoadFromSQLServer _ ServerName:="MyServer", _ ServerUserName:="MyUserID", _ ServerPassword:="MyPassword", _ PackageName:="DTSDemo" dtsp.Execute End Sub
*************************************
I can Run the package direct from SQL server but get error by Vb program. Any idea why it is so.
This is my procedure and the error is incorrect syntax near '01'
DECLARE @returnDay int
--Looking at current date, SELECT @returnDay = DatePart(day,GetDate()) --If is the 7th of the current moth then If @returnDay = 24
EXEC master.dbo.xp_sendmail @query = 'SELECT a.HospitalName,a.HospitalCode,c.ProductName,b.UnitsDiscarded,d.FateOfProducts,b. DateEntered, b.DateCompleted,b.CompiledBy FROM test.dbo.Units b inner join Hospitals a ON (a.HospitalID = b.HospitalID) inner join Products c ON (b.ProductID = c.ProductID) inner join FateOfProducts d ON (d.FateID = b.FateID) where b. DateEntered = DateAdd(month, -1, Convert(CHAR(8), GetDate(), 121) + '01') order by a.HospitalID', @recipients=test@hotmail.com', @message='Submitting Results for the previous month', @subject=' results for previous month', @attach_results = 'true', @separator = '/s'
SELECT @@ERROR As ErrorNumber
What am I missing here now, I am quite new to stored procedures
When im testing in local machine... my app works fine... but when i publish it on server... the sql DateTime parameter get an error: ERROR ON SERVER : String was not recognized as a valid DateTime my code:SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["StringDeConexao"].ConnectionString); SqlCommand oCmd = new SqlCommand("spcCadLjItem", con);oCmd.CommandType = CommandType.StoredProcedure;
oCmd.Connection.Open();SqlTransaction trans = con.BeginTransaction(); oCmd.Transaction = trans; oCmd.Parameters.Add(new SqlParameter("@dt_exclusao", SqlDbType.DateTime)); oCmd.Parameters["@dt_exclusao"].Value = DBNull.Value; oCmd.ExecuteNonQuery(); When I inspect the type of parameter on my machine its ok.. SqlDbType its DateTime... and runs perfectly...Why it doesnt work when i publish on server??????? tks!!
Hi, I am using Sql database in my asp.net application. the code runs fine on the machine where i m developing but when I try to run the code on other machine it gives following error-- error is related to access to database.(sql personal server is installed on local machine) I m giving the following connection string--- "Server=localhost;UID=sa;PWD=mypassword;Database=try1" I have reinstalled the sql server using mixed mode authentication and the same sa password but still problem continues.. THE ERROR IT GIVES IS--- Server Error in '/try1' Application.
SQL Server does not exist or access denied. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.Data.SqlClient.SqlException: SQL Server does not exist or access denied.Source Error:
Line 49: SqlCommand cmdSelect; Line 50: cmdSelect = new SqlCommand("select * FROM Departments", sqlConn); Line 51: sqlConn.Open(); Line 52: return cmdSelect.ExecuteReader(CommandBehavior.CloseConnection); Line 53: }Source File: c:inetpubwwwroot ry1DataAccessCode.cs Line: 51 Stack Trace:
[SqlException: SQL Server does not exist or access denied.] System.Data.SqlClient.ConnectionPool.GetConnection(Boolean& isInTransaction) System.Data.SqlClient.SqlConnectionPoolManager.GetPooledConnection(SqlConnectionString options, Boolean& isInTransaction) System.Data.SqlClient.SqlConnection.Open() try1.DataAccessCode.getDept() in c:inetpubwwwroot ry1DataAccessCode.cs:51 try1.WebForm1.Page_Load(Object sender, EventArgs e) in c:inetpubwwwroot ry1Login.aspx.cs:35 System.Web.UI.Control.OnLoad(EventArgs e) System.Web.UI.Control.LoadRecursive() System.Web.UI.Page.ProcessRequestMain()
Version Information: Microsoft .NET Framework Version:1.1.4322.573; ASP.NET Version:1.1.4322.573
I have a stored proceedure (which I will tag on at the end for those interested) which is taking at least 15 minutes to run when executed, but completes in 1 minute when the tsql statement is run in Query Analyser. Why is this?
I suspect that it may be connected to table indexing, but why then is this bypassed when QA is used?
Any advice appreciated.
Derek
************************************************** *********************** IF EXISTS (SELECT * FROM sysobjects WHERE id = object_id(N'dbo.sp_ValidateAIGL') AND OBJECTPROPERTY(id, N'IsProcedure') = 1) DROP PROCEDURE dbo.sp_ValidateAIGL GO
-- *** Global Non Program Specific Data Errors *** -- CHECK - that there are records in the DEB_IGL_PAYROLL_OUTPUT file.....none and the routine failed... IF NOT EXISTS(SELECT * FROM tbl_OUT_Payroll WHERE IGLProgramID = @IGLProgramID) INSERT INTO #IGLErrors SELECT NULL, 100, 'No records were processed by the IGL run!'
SELECT * FROM #IGLErrors
-- CHECK - search for any records where the employee's EXPENSE_CODE is NULL INSERT INTO #IGLErrors SELECT DISTINCT NULLIF(EmpNo, ''), 2, 'Employee "' + COALESCE(NULLIF(RTRIM(EmpNo), ''), '<Missing Employee>') + '" (Organisation Unit - ' + COALESCE(RTRIM(OrgUnitCode), '<No Organisation Unit>') + ') does not have a EXPENSE_CODE Code.' FROM tbl_OUT_Payroll WHERE NULLIF(ExpenseCode, '') IS NULL ANDIGLProgramID = @IGLProgramID
SELECT * FROM #IGLErrors -- CHECK - check that the BALANCE of DEBITs match the balance of CREDITs IF (SELECT SUM(Cash) FROM tbl_OUT_Payroll WHERE IsCredit = 1 AND IGLProgramID = @IGLProgramID) <> (SELECT SUM(Cash) FROM tbl_OUT_Payroll WHERE IsCredit = 0 AND IGLProgramID = @IGLProgramID) INSERT INTO #IGLErrors SELECT NULL, 3, 'The total cash value for DEBIT elements does not match the total cash for CREDIT elements.'
SELECT * FROM #IGLErrors -- *** Program 1 and 2 errors *** IF @IGLProgramID IN (1, 2) BEGIN -- CHECK - search for any records where the employee's COST_CENTRE is NULL INSERT INTO #IGLErrors SELECT DISTINCT NULLIF(EmpNo, ''), 1, 'Employee "' + NULLIF(RTRIM(EmpNo), '') + '" (Organisation Unit = ' + RTRIM(OrgUnitCode) + ') does not have a COST_CENTRE Code.' FROM tbl_OUT_Payroll WHERE NULLIF(CostCenter, '') IS NULL ANDIGLProgramID = @IGLProgramID
SELECT * FROM #IGLErrors
-- Check for EMPLOYEEs that were not transfered to the PAYROLL output (usually caused by missing ORG_UNITs or not picked up in -- the DEB_VIEW_APPOINTEE view...) INSERT INTO #IGLErrors SELECT DISTINCT EMP_NO, 11, 'Employee "' + RTRIM(EMP_NO) + '" was excluded from the summary. Check their Organisation Unit codes!' FROM PSELive.dbo.COSTING_OUTPUT WHERENOT EMP_NO IN (SELECT DISTINCT EmpNo FROM tbl_OUT_Payroll WHERE IGLProgramID = @IGLProgramID) ANDPERIOD_NO = @PeriodNo ANDTAX_YEAR = @TaxYear
SELECT * FROM #IGLErrors
-- Check that there are no ELEMENTS in the COSTING_OUTPUT table that don't exist in the tbl_IGLElements table INSERT INTO #IGLErrors SELECT DISTINCT ELEMENT, 12, 'Element "' + RTRIM(ELEMENT) + '" does not exist in the IGL Interface Elements table!' FROM PSELive.dbo.COSTING_OUTPUT WHERE ELEMENT NOT IN ( SELECT DISTINCT Element FROM tbl_IGLElements ) ANDPERIOD_NO = @PeriodNo
SELECT * FROM #IGLErrors
END
-- *** Add a error to indicate the number of errors *** IF EXISTS (SELECT * FROM #IGLErrors) INSERT INTO #IGLErrors SELECT 0, 0, 'Warning, there are ' + CAST(Count(*) AS VarChar(5)) + ' recorded errors!' FROM#IGLErrors
-- Transfer the records to the ErrorsLog table ready for the user to view... DELETE FROM tbl_SYSErrorsLog INSERT INTO tbl_SYSErrorsLog (IGLProgramID, OutputLogID, KeyField, ErrorID, Description) SELECT@ProgramLogID, @IGLPeriodID, KeyField, ErrorID, Description FROM #IGLErrors ORDER BY ErrorID
DROP TABLE #IGLErrors
SELECT * FROM tbl_SYSErrorsLog ORDER BY ErrorID
--SET NOCOUNT OFF
GO GRANT EXECUTE ON dbo.sp_ValidateAIGL TO Public GO
I have one drop and create procedure script in one sql session and execute the procedure in other session. Now when i am compiling the procedure in first session, it gets completed successfully.
Now when i move to other session and try to execute the procedure, it gives me error saying :
"Invalid column name 'ColumnName'."
Now when I execute the procedure in same session in which procedure was compiled, it runs successfully. Once run, I go back to my other session and it runs again.
When i run it from sql server data tools on the test box it runs fine. However when i run it from the ssisdb directly i get the below error.
reload table tablename1 from Excel file:Error: The "filetoload.Outputs[Excel Source Output].Columns[Product]" failed because truncation occurred, and the truncation row disposition on "filetoload.Outputs[Excel Source Output].Columns[Product]" specifies failure on truncation. A truncation error occurred on the specified object of the specified component.
reload table t from Excel file:Error: There was an error with filetoload.Outputs[Excel Source Output].Columns[Product] on filetoload.Outputs[Excel Source Output]. The column status returned was: "Text was truncated or one or more characters had no match in the target code page.".
Why does Error log show database restarting everytime a transactionlog backup runs?It also runs a checkdb as well.The log backups are scheduled through a maintenance plan.Is this normal?
I try to make SSSIS packages made on my pc accesible to an other user of SSIS (both running on Windows 2000). The packages are on a shared drive in our LAN.. Some configurationfiles are use to configure the Oracle DBconnection.The same files are on the same location on both PC's
The other user can open and run the packages but from the moment the lookup buffers are loaded, we get the following errors:
Error: 0xC0202009 at AB_ADDRESS_DF, LOOKUP_POST_ID [22801]: An OLE DB error has occurred. Error code: 0x80004005.
An OLE DB record is available. Source: "OraOLEDB" Hresult: 0x80004005 Description: "".
Error: 0xC020824E at AB_ADDRESS_DF, LOOKUP_POST_ID [22801]: OLE DB error occurred while populating internal cache. Check SQLCommand and SqlCommandParam properties.
Error: 0xC004701A at AB_ADDRESS_DF, DTS.Pipeline: component "LOOKUP_POST_ID" (22801) failed the pre-execute phase and returned error code 0xC020824E.
Running eval. edition of Sql Server Standard 2005. "Insufficient product level" error is thrown during validation phase of an OleDBCommand data flow task. This task type is not licensed in Sql Server 2005 standard? The component runs a very simple sql update statement against a one row table in Sql Server 2005.
If it works from BIDS, should it not work from dtexec.exe on the same box?
Does dtexec run under the security context of the logged in user?
I have simple query which creates tables by passing database name as parameter from a parameter table .
SP1 --> creates databases and calls SP2--> which creates tables . I can run it fine via SSMS but when I run it using SSIS it fails with below error .The issue gets more interesting when it fails randomly on some database creation and some creates just fine .
Note** I am not passing any database of name '20'
Exception handler error :
ERROR :: 615 :: Could not find database ID 20, name '20'. The database may be offline. Wait a few minutes and try again. ---------------------------------------------------------------------------------------------------- SPID: 111 Origin: SQL Stored Procedure (SP1) ---------------------------------------------------------------------------------------------------- Could not find database ID 20, name '20'. The database may be offline. Wait a few minutes and try again. ----------------------------------------------------------------------------------------------------
Error in SSIS
[Execute SQL Task] Error: Executing the query "EXEC SP1" failed with the following error: "Error severity levels greater than 18 can only be specified by members of the sysadmin role, using the WITH LOG option.". Possible failure reasons: Problems with the query, "ResultSet" property not set correctly, parameters not set correctly, or connection not established correctly.I have sysadmin permission .
I have an SSIS package that runs fine through command pormpt although when I try to run it from a SQL Servr Agent Job CmdExec step it bombs out. Please help this has me stumped...the SSIS package uses an XML connection string so certain key settings such as connection strings and email info can be changed easily. Currently this is all on the same machine. I have not moved it beyond where I am developing.
On the command line I am using the following command...
Microsoft (R) SQL Server Execute Package Utility Version 9.00.1399.06 for 32-bit Copyright (C) Microsoft Corp 1984-2005. All rights reserved.
Started: 6:59:40 PM Progress: 2006-08-16 18:59:41.29 Source: Data Flow Task Validating: 0% complete End Progress Progress: 2006-08-16 18:59:41.29 Source: Data Flow Task Validating: 33% complete End Progress Progress: 2006-08-16 18:59:41.71 Source: Data Flow Task Validating: 66% complete End Progress Progress: 2006-08-16 18:59:41.73 Source: Data Flow Task Validating: 100% complete End Progress Progress: 2006-08-16 18:59:41.77 Source: Data Flow Task Validating: 0% complete End Progress Progress: 2006-08-16 18:59:41.77 Source: Data Flow Task Validating: 33% complete End Progress Progress: 2006-08-16 18:59:41.77 Source: Data Flow Task Validating: 66% complete End Progress Progress: 2006-08-16 18:59:41.77 Source: Data Flow Task Validating: 100% complete End Progress Progress: 2006-08-16 18:59:41.79 Source: Data Flow Task Prepare for Execute: 0% complete End Progress Progress: 2006-08-16 18:59:41.79 Source: Data Flow Task Prepare for Execute: 33% complete End Progress Progress: 2006-08-16 18:59:41.79 Source: Data Flow Task Prepare for Execute: 66% complete End Progress Progress: 2006-08-16 18:59:41.79 Source: Data Flow Task Prepare for Execute: 100% complete End Progress Progress: 2006-08-16 18:59:41.81 Source: Data Flow Task Pre-Execute: 0% complete End Progress Progress: 2006-08-16 18:59:41.84 Source: Data Flow Task Pre-Execute: 33% complete End Progress Progress: 2006-08-16 18:59:41.90 Source: Data Flow Task Pre-Execute: 66% complete End Progress Progress: 2006-08-16 18:59:41.90 Source: Data Flow Task Pre-Execute: 100% complete End Progress Progress: 2006-08-16 18:59:41.92 Source: Data Flow Task Post Execute: 0% complete End Progress Progress: 2006-08-16 18:59:41.92 Source: Data Flow Task Post Execute: 33% complete End Progress Progress: 2006-08-16 18:59:41.92 Source: Data Flow Task Post Execute: 66% complete End Progress Progress: 2006-08-16 18:59:41.92 Source: Data Flow Task Post Execute: 100% complete End Progress Progress: 2006-08-16 18:59:41.92 Source: Data Flow Task Cleanup: 0% complete End Progress Progress: 2006-08-16 18:59:41.93 Source: Data Flow Task Cleanup: 33% complete End Progress Progress: 2006-08-16 18:59:41.93 Source: Data Flow Task Cleanup: 66% complete End Progress Progress: 2006-08-16 18:59:41.93 Source: Data Flow Task Cleanup: 100% complete End Progress Progress: 2006-08-16 18:59:41.95 Source: Send Mail Task The SendMail task is initiated.: 0% complete End Progress Progress: 2006-08-16 18:59:42.09 Source: Send Mail Task The SendMail task is completed.: 100% complete End Progress DTExec: The package execution returned DTSER_SUCCESS (0). Started: 6:59:40 PM Finished: 6:59:42 PM Elapsed: 1.984 seconds
When I try to use the same command within SQL Server Agent Job using a CmdExec step I get the following error...
Description: The package is attempting to configure from the XML file "S:connectionscontacts.dtsConfig". End Info Warning: 2006-08-16 18:40:03.15 Code: 0x80012012 Source: contactsPackage Description: The configuration file name "S:connectionscontacts.dtsConfig" is not valid. Check the configuration file name. End Warning Warning: 2006-08-16 18:40:03.15 Code: 0x80012059 Source: contactsPackage Description: Failed to load at least one of the configuration entries for the package. Check configurations entries and previous warnings to see descriptions of which configuration failed. End Warning Info: 2006-08-16 18:40:03.20 ... Process Exit Code 1. The step failed.
Hi: I have created the following trigger. alter trigger deletecategories on Product_Tbl_ProductDetailsfor delete as delete CategoryID from Product_Tbl_Catagory,Product_Tbl_ProductDetailswhere Product_Tbl_Catagory.CategoryID=Product_Tbl_ProductDetails.CategoryIDdelete SubcategoryID from Product_Tbl_SubCatagory,Product_Tbl_ProductDetailswhere Product_Tbl_SubCatagory.SubcategoryID=Product_Tbl_ProductDetails.SubcategoryID While deleting the record "delete from Product_Tbl_ProductDetails where CategoryID=1"I have encountered the below error Error:Msg 208, Level 16, State 1, Procedure deletecategories, Line 4Invalid object name 'CategoryID'. Can any one send me the correct query Thanks:Suresh
When I execute a query that updates multiple rows, the trigger issues an error. Does anyone see the problem ?
Listed below is the Error, Trigger, and Query.
Server: Msg 512, Level 16, State 1, Procedure TR_KYLAB_LOT_GRADE_01, Line 5 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.
CREATE TRIGGER TR_KYLAB_LOT_GRADE_01 ON KYLAB_LOT_GRADE FOR UPDATE NOT FOR REPLICATION AS Update KYLAB_LOT_GRADE SET updateUserName = user_name(), updateDateTime = getdate() WHERE KYLAB_LOT_GRADEID = ( SELECT INSERTED.KYLAB_LOT_GRADEID FROM INSERTED)
UPDATE KYLAB_LOT_GRADE SET OLD_ITEM = 'TEST' WHERE ITEM_TYPE_ID = 'FG' AND ITEM_NO = '2011312LV0' AND LOT_NO IN ('1000', '1001')
Hi everybody, My SQL 2000 refuses to recognize the INSTEAD OF trigger. I just pasted a query from the SQL Server Books Online article "Designing INSTEAD OF Triggers" into the Query Analyzer and was greeted with:
Server: Msg 170, Level 15, State 1, Procedure IO_Trig_INS_Employee, Line 2 Line 2: Incorrect syntax near 'INSTEAD'.
The following trigger is in a table called "PERSON". When I attempt to save it (not even testing it yet), I get the message "Incorrect syntaxt near 'GO'". Please advise as to what the error might be.
CREATE TRIGGER InsertHeadCount ON dbo.person AFTER INSERT AS INSERT INTO HEADCOUNT(person_id,activity_id,no_answer,not_coming,coming) SELECT i.person_id,a.activity_id,1,0,0 FROM INSERTED i CROSS JOIN ACTIVITY a GO
Background: I'm building an application that includes tables PERSON, ACTIVITY, and HEADCOUNT that look like this:
PERSON person_id (int) person_name (varchar(50)) ...etc
The intended functionality of the trigger is as follows: Suppose that:
a) The ACTIVITY table is already populated with several records, say with activity_id = 1, 2, and 3. b) The HEADCOUNT table is already populated with 30 records.
TRIGGER OBJECTIVE: When a new record is added to the PERSON, say with person_id= 10, insert one record in the HEADCOUNT table FOR EACH activity in the ACTIVITY table for that person. Thus, if person #10 is added to the PERSON table, then the trigger would add the following records to the HEADCOUNT table:
I made a trigger for delete just like this."CREATE TRIGGER [MbPromoHdrDel] ON [dbo].[MbPromo_hdr]FOR DELETEASDeclare @severity int,@IdNmbr nvarchar(10)Set @Severity = 0Declare NoId Cursor Local Static forSelect [Promo_Id] from deletedOpen NoIdWhile 1=1BeginFetch NoId Into@IdNmbrIf @@Fetch_Status <> 0BreakIf Exists (Select 1 from MbPromo_dtl where [Promo_Id]=@IdNmbr)Set @Severity = @Severity+1ElseBeginDelete From MbPromo_hdr where [Promo_Id]=@IdNmbrEndEndClose NoIdDeallocate NoIdIf @Severity = 0CommitElseBeginRollBackPrint 'Data Cannot Be delete'EndGo"When i delete the record from Enterprise manager it give me an error"Another user has modified the content of this table or view. The databaserow you are modifying no longer exists in the database."Why? And it happen with all of the record at my table--Message posted via http://www.sqlmonster.com
I have a table:----------------------------------------------------CREATE TABLE CATEGORY (CATEGORY_ID INTEGER IDENTITY(1,1) NOT NULL,CATEGORY_NAME VARCHAR(40) NOT NULL,PARENT_CATEGORY_ID INTEGER,CATEGORY_ICON IMAGE,DEPTH INTEGER,CONSTRAINT PK__CATEGORY PRIMARY KEY (CATEGORY_ID))GO----------------------------------------------------and i try to create this trigger, but i fail:----------------------------------------------------CREATE TRIGGER [AI_CATEGORY] ON [dbo].[CATEGORY]FOR INSERTASDECLARE @TEMP_ID AS INT, @COUNTER AS INTUPDATE AI_CATEGORYSET @TEMP_ID = CATEGORY_ID, @COUNTER = 1IF PARENT_CATEGORY_ID IS NOT NULLBEGINWHILE@TEMP_ID IS NOT NULLBEGINUPDATE AI_CATEGORYSET @TEMP_ID = PARENT_CATEGORY_ID,@COUNTER = @COUNTER + 1ENDENDUPDATE CATEGORYSET DEPTH = @COUNTER----------------------------------------------------And i get the following Error using SQL Server 2000:Server: Msg 207, Level 16, State 3, Procedure AI_CATEGORY, Line 7Invalid column name 'PARENT_CATEGORY_ID'.Any clue?Coosa
I have the following CREATE TRIGGER dbo.tgrCacheCustomers ON dbo.Customers FOR INSERT, UPDATE, DELETE AS EXEC sp_makewebtask 'C:DependencyFile.txt','SELECT top 1 CustomerId FROM customers' and I get the following error that I dont understand:
Error 21037: [SQL-DMO] The name specified in the Text property's 'CREATE ...' statement must match the Name property, and must be followed by valid TSQL statements.
The trigger does set my CommAudit field to 1 when imaSlsCls is changed, but at the end of the day when I issue the UPDATE command to set all CommAudit back to 0 I get an error. Is there a differant way to make it work?? See trigger, update command & error below. Thanks for any help, Tom
*** TRIGGER *** CREATE TRIGGER [tblItemMaster_utr] ON dbo.tblItemMaster FOR UPDATE AS IF (select imaSlsCls from inserted) <> (select imaSlsCls from deleted) BEGIN update tblItemMaster set commaudit = 1 from inserted, tblItemMaster where inserted.imaitnbr = tblItemMaster.imaitnbr END
*** UPDATE COMMAND *** UPDATE tblItemMaster SET CommAudit = 0 WHERE CommAudit = 1
*** ERROR *** Server: Msg 512, Level 16, State 1, Procedure tblItemMaster_utr, Line 5 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.
I have setup transactional replication between 2 computers.
In the publisher, there is a INSTEAD OF DELETE trigger to prevent deletion of any rows in a table. If an attempt to delete rows in that table occurs, this trigger will write the deleting rows to a local file C:
empyyyy.mm.dd.hh.mm.ss.tbl_deleted.csv, and then email this file to a list of recipients. This trigger only exists in the publisher.
Yesterday, while I'm working on the publisher DB, I accidentally executed a stored procedure which attempted to delete some rows in the table. The trigger fired, a file C:2012.09.04.09.01.01.tbl_deleted.csv generated, and the email was sent. But then problem occurs.
Problem: When I open replication monitor, I see a bunch of errors in "Distributor To Subscriber History". The error said: Command attempted:
Similar errors occur periodically, and the filename (C: empyyyy.mm.dd.hh.mm.ss.tbl_deleted.csv) in the error messages reflect the actual time of the error.
Please can anyone help me code the trigger below. I have had errors pointing to "sp_configure 'SQL Mail XPs', 1;" and "RECONFIGURE", that this lines should be not where I have placed them. I have tried other combinations and have not worked at all! Is any other ways I can achieve this all?
Code Snippet
CREATE TRIGGER reminder ON Bug_Report FOR INSERT, UPDATE, DELETE AS sp_configure 'SQL Mail XPs', 1; EXEC master..xp_sendmail 'MaryM', 'Don't forget to print a bug report.' RECONFIGURE
hi....... i create a trigger after delete which work perfactly fine on one sqlserver2005 machine but not at another.......machine having sqlserver2005 this trigger effect 15 tables from which i am deleting data...when trigger fires..... now it cause following error when i fire ir on another machine error source: .net sql client data provider error message:maximun stored procedure,triggers,functions,or view nesting level exceeded (limit 32) plzzzz give da solution.....its really frustrating me.... thanks in advance
The many that I have spoken to all are clueless on this one. Thanks in advance for the right solution!
The insert trigger I created works fine (well, nearly fine), except that AFTER the first insert operation (ie second, third etc), it always produces the correct results BUT FOR THE PREVIOUS INSERTED ROW. It is as if there is a latency of one row in the temp table INSERTED.
I would greatly appreciate a 'why', and more importantly, a 'how to fix it' for this problem.
If you need to look at the code, a NOTEPAD file is attached.
Much appreciated
--start trigger-- create trigger UpdateAffiliateEarnings on Orders for insert, update as
--check existence of affiliateid, and for product type select @AffID=AffID, @ProductType=Source from Orders where AffID IS NOT NULL
--get relevant information if @AffID IS NOT NULL begin if @ProductType = 'FLOWER' begin select @Earnings=CONVERT(money,ChargedAmount*CommissionRa te) from Orders o,FlowerOrder t,Commission c where o.OrderID = t.OrderID and t.CommissionID = c.CommissionID and PaymentConfirmedYN='YES' end if @ProductType='PHONE' begin select @Earnings=CONVERT(money,ChargedAmount*CommissionRa te) from Orders o,PhoneOrder t,Commission c where o.OrderID = t.OrderID and t.CommissionID = c.CommissionID and PaymentConfirmedYN='YES' end
--update Affiliate account --get totals to update select @CurrentEarnings=AffTotalEarnings, @AffTotalPayments=AffTotalPayments from Affiliates where AffID=@AffID
--calculate new totals for affiliate account set @AffTotalEarnings=@CurrentEarnings+@Earnings set @AffOutstandingBalance=@AffTotalEarnings-@AffTotalPayments
--update affiliate account to new totals update Affiliates set AffTotalEarnings=@AffTotalEarnings, AffOutstandingBalance=@AffOutstandingBalance where AffID=@AffID
--roll back the transaction if there is an error if @@ERROR !=0 rollback tran end -- end of trigger --
Thanks for looking at this post. I currently have a trigger that fires when a row is inserted or deleted on a table. The idea behind the trigger is that when a row is inserted (representing a sub-category for images), the categories parent needs to have some work done on it. I currently have the trigger working just fine with single inserts and single deletes:
sql Code:
Original - sql Code
CREATE TRIGGER smvcModImageManagerCategory_insert_delete_pdfManger_sync ON smvcModImageManagerCategory FOR INSERT, DELETE AS DECLARE @pdfId INTEGER; DECLARE @parentPdfId INTEGER; DECLARE @grandparentPdfId INTEGER; DECLARE @parentId INTEGER; DECLARE @grandparentId INTEGER; DECLARE @tableName VARCHAR( 255 );
-- If I am being inserted or deleted, and I am not a top level -- category, then my parent's pdf record needs to be set so that -- the pdf file is updated IF (SELECT id FROM Inserted) IS NOT NULL BEGIN SELECT @pdfId = (SELECT pdfManagerId FROM Inserted), @parentId = (SELECT parentCategory FROM Inserted), @grandparentId = (SELECT parentCategory FROM smvcModImageManagerCategory WHERE id = @parentId); END ELSE BEGIN SELECT @pdfId = (SELECT pdfManagerId FROM Deleted), @parentId = (SELECT parentCategory FROM Deleted), @grandparentId = (SELECT parentCategory FROM smvcModImageManagerCategory WHERE id = @parentId) END
-- If I am not a top level category, set my parent's pdf to be -- updated IF @parentId <> -1 BEGIN SELECT @parentPdfId = (SELECT pdfManagerId FROM smvcModImageManagerCategory WHERE id = @parentId); UPDATE smvcModPdfManager SET data_last_updated = GETDATE() WHERE id = @parentPdfId; END GO
CREATE TRIGGER smvcModImageManagerCategory_insert_delete_pdfManger_syncON smvcModImageManagerCategoryFOR INSERT, DELETEAS DECLARE @pdfId INTEGER; DECLARE @parentPdfId INTEGER; DECLARE @grandparentPdfId INTEGER; DECLARE @parentId INTEGER; DECLARE @grandparentId INTEGER; DECLARE @tableName VARCHAR( 255 ); -- If I am being inserted or deleted, and I am not a top level -- category, then my parent's pdf record needs to be set so that -- the pdf file is updated IF (SELECT id FROM Inserted) IS NOT NULL BEGIN SELECT @pdfId = (SELECT pdfManagerId FROM Inserted), @parentId = (SELECT parentCategory FROM Inserted), @grandparentId = (SELECT parentCategory FROM smvcModImageManagerCategory WHERE id = @parentId); END ELSE BEGIN SELECT @pdfId = (SELECT pdfManagerId FROM Deleted), @parentId = (SELECT parentCategory FROM Deleted), @grandparentId = (SELECT parentCategory FROM smvcModImageManagerCategory WHERE id = @parentId) END -- If I am not a top level category, set my parent's pdf to be -- updated IF @parentId <> -1 BEGIN SELECT @parentPdfId = (SELECT pdfManagerId FROM smvcModImageManagerCategory WHERE id = @parentId); UPDATE smvcModPdfManager SET data_last_updated = GETDATE() WHERE id = @parentPdfId; ENDGO
However, when I execute a statement like:
sql Code:
Original - sql Code
DELETE FROM smvcModImageManagerCategory WHERE (smvcModImageManagerCategory.id IN ('86','87','88','90','91'))
DELETE FROM smvcModImageManagerCategory WHERE (smvcModImageManagerCategory.id IN ('86','87','88','90','91'))
I get an error because the virtual 'Deleted' table has more than one record in it. So, what I really need is advice on how to turn the above trigger into something that will be able to handle multiple deletes.
[code = "sql"]CREATE TRIGGER Trigger_20321 ON FACT_CUST_GRP_ICM_MO AFTER DELETE AS /* DELETE trigger on FACT_CUST_GRP_ICM_MO */ /* default body for Trigger_20321 */
[Code]...
Msg 102, Level 15, State 1, Procedure Trigger_20321, Line 21 Incorrect syntax near ')'.
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