Which Trigger Executes First?

Mar 10, 2006

Hi!



I have 2 DBs.

DB1
MID
event
date

DB2
MID
event
date
tag (incremented by 1)

DB1 contains a log of multiple events for each record while DB2 contains the latest log for the record. I have a trigger(trigger1) in DB1 that automatically updates/inserts the log in DB2 depending on whether the record already exists in DB2.

I also have another trigger that checks for a specific value in the 'tag' field.

I used to set this trigger(trigger2) up in DB2 but it was executed twice. The first one when trigger1 inserts/updates a DB2 record and the second one when trigger2 updates DB2. So instead of having only a value of 1 in tag, I get a 2.

So what I did is I moved trigger2 to DB1. My only problem is I don't know which trigger get executed first.

I'm not sure whether this is the best way of updating the 'tag' field. The purpose of the tag field is that when it reaches a certain number, it stops all events and inserts a termination log in DB2.

View 2 Replies


ADVERTISEMENT

Delete Data Before Trigger Executes

Jan 12, 2004

I am trying to delete data from a table prior to populating with new data via a trigger if certain critria matches to eliminate duplicates. I have copied the trigger below. The syntax checks ok but I get any error message saying 'Incorrect syntax near 'GO'. 'ALTER TRIGGER' must be the first statement in a query batch' when I try to save.

Can someone tell me if this is possible please.

IF EXISTS (SELECT * FROM hold_complete
WHERE fkey = hold_complete.fkey AND actiontext = 'hold' and Subactiontext = 'pending user')
delete from hold_complete where hold_complete.fkey = fkey
GO
CREATE TRIGGER tr_hold_complete ON CallsHistory
for INSERT AS
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
insert hold_complete
select ins.AddedDT, ins.fkey, ins.actiontext,
ins.subactiontext, con.emailaddress, ca.loggeddt,
(con.forename + ' ' + con.surname) as contactname,
ca.summary, ca.notes,co.coordinator, co.coordinator,getdate(), ca.status,ca.lastsubaction,getdate(),ca.dateopened ,ca.companyname,getdate(),(null),ch.notes
FROM inserted as ins with (nolock)
join calls as ca with (nolock)on
ins.fkey = ca.callid
join contact as con with (nolock) on
ca.contactid = con.contactid
join company as co with (nolock) on
ca.companyid = co.companyid
join callshistory as ch with (nolock) on
ins.historyid = ch.historyid
where ins.actiontext = 'hold' and ins.Subactiontext in ('completed','pending user')

View 9 Replies View Related

Job Executes Only First Step

Feb 13, 2006

I have three stored procedures that need to run nightly in SQL 7. The threeprocedures are not related; but to keep the procedures from running at thesame time, I placed them as three steps of a single job. The first two stepsare set to "Goto next step" on success; the last step is set to "Quit withsuccess."The job runs every night. However, only the first step/procedure isexecuted. Also, the first step has a green flag next to its ID in the Stepstab of the job propertiesI suppose I could just call all three SPs from a single stored procedurethat is run nightly. But I thought that putting them as three steps in asingle job would cause all three to run. What am I doing wrong?Thanks!Neil

View 2 Replies View Related

SAVED DTS JOB ONLY EXECUTES FOR CREATOR???

Jun 7, 2000

I have a developer using SQL 7.0 Enterprise Manager and the DTS Wizard to create and save simple DTS imports on the SQL Server. The DTS job runs only on his workstation using his NT logon ID. Server is set for mixed security.
Other users can edit the saved DTS job and resave it, then anyone can run the job. I tried having the developer log in with his NT logon ID on another workstation; he can't run the job from there if he was the last person to edit it from his workstation.

Any ideas, anyone? This is the only person having this problem in my shop.

Thanks!

View 3 Replies View Related

Script Executes Ok But No Results

Apr 2, 2014

I am trying to bulk map products to a catergoryID table. Each product has a SKU code and then is mapped to a CategoryID table. The script executes fine but when I look the products are not mapped.

create table tmp_products (ProductID int, SKU nvarchar(100) collate SQL_Latin1_General_CP1_CI_AS, CategoryID int)

insert into tmp_products (SKU, CategoryID) values ('CLFLNW1',1252)
insert into tmp_products (SKU, CategoryID) values ('CLFROCR013',1252)
insert into tmp_products (SKU, CategoryID) values ('GBLGOKOM',1252)
insert into tmp_products (SKU, CategoryID) values ('HS008714',1252)
insert into tmp_products (SKU, CategoryID) values ('HS014928',1252)

[Code] .....

View 3 Replies View Related

View Executes Too Slow

Jun 22, 2006

i have written a query and created it as a view

when i run the query it takes less that 5 seconds to give results

but when i run the view it takes about a minute

can anyone help please, it keeps giving me time out errors

here is the query.


SELECT
MAX(B.Code) AS Code,
MAX( T.Description) AS Type,
MAX( WH.Description) AS Warehouse,
MAX(B.Barcode) AS Barcode,
MAX(B.BatchNo) AS BatchNo,
MAX(B.CustomField) AS CustomField,
MAX(B.Colour) AS Colour,
MAX(Q.Quality) AS Quality,
MAX(round( M.ConvFactor, 2, 2)) AS ConvFactor,
MAX( M.Multiply) AS Multiply,
MAX(CONVERT(VARCHAR(20),
round((B.BoughtQty + B.TransferQty + B.IssuedQty + B.ReturnedQty + B.AdjustmentQty), 2)))
+ ' ' + MAX( M.UoM) AS Available,
CASE WHEN MAX( M.Multiply) = 'M'
THEN MAX(CONVERT(VARCHAR(20),
round(((B.BoughtQty + B.TransferQty + B.IssuedQty + B.ReturnedQty + B.AdjustmentQty) * M.ConvFactor), 2)))
+ ' ' + MAX(M.AUoM)
ELSE max(CONVERT(Varchar(50),convert(float,
round(((B.BoughtQty + B.TransferQty + B.IssuedQty + B.ReturnedQty + B.AdjustmentQty) / M.ConvFactor), 2))) )
+ ' ' + MAX( M.AUoM)
END AS AvailableAlternative,
MAX(BC.Supplier) AS Supplier,
MAX( OD.SupplierCode) AS SupplierCode
FROM cvrbatches B
LEFT JOIN SciposA.dbo.cvrmaster M ON M.Code = B.Code
LEFT JOIN cvrbatchctrl BC ON B.Code = BC.Code
AND B.Type = BC.Type
AND B.BatchNo = BC.BatchNo
INNER JOIN SciposA.dbo.cvrwhcontrol WH ON WH.Warehouse = B.Warehouse
INNER JOIN SciposA.dbo.cvrtypes T ON T.CoverType = B.Type
INNER JOIN cvrquality Q ON Q.Code = B.Quality AND B.Type = Q.Type
LEFT JOIN SciposA.dbo.cvrgrndetail GD ON GD.BatchNo = B.BatchNo AND B.Warehouse = GD.Warehouse
LEFT JOIN SciposA.dbo.cvrorderdetails OD ON OD.OrderNo = GD.OrderNo AND OD.LineN = GD.LineN
GROUP BY B.Barcode

View 6 Replies View Related

Sort And Select, Which Executes First?

Sep 15, 2006

I use SQL Server 2005.

I want to split the data in a table into two parts, say 30%-70%.

Here are my query statements:

-- 30%

SELECT top 30 percent * FROM DataTable ORDER BY Col1

--70%

SELECT top 70 percent * FROM DataTable ORDER BY Col1 DESC

Somebody says the result is not guaranteed to be correct since in SQL Server 2005, the query optimizer may choose different strategy to execute the query statement.

I think select should execute after order by, which has nothing to do with query optimization. Am I correct?





View 4 Replies View Related

Nested Executes In Insert Statements

Mar 19, 2001

Is this a limitation of SQL server. I am running a quite complex sp that I wrote which uses exec to execute an SQL string. Running the SP produces the desired results but if I try to use this sp with an insert statement then I get an error message that exec cannot be nested in an insert statement.....any help would be appreciated

View 2 Replies View Related

Visual Basic Executes DTS Package

Jan 12, 2005

I have created a rule in outlook to run this Visual Basic Script when I receive a specific email. The codes runs a SQL Server DTS Package that imports data and runs a couple of stored procs. If the DTS package takes a while to execute my outlook will lock up until the entire package is complete. I want to run the DTS package to run but I don’t want the application to remain locked till its complete. Anyone have any ideas of how to get around this....


Public Sub RunTVDTSPackage(Item As Outlook.MailItem)
Dim oPackage As New DTS.Package
On Error GoTo eh

oPackage.LoadFromSQLServer "DummyServerName", "DummyUser", "DummyPSWd", _
DTSSQLStgFlag_Default, _
"", "", "", "Top_Customer - TV", 0
'Execute the Package

oPackage.Execute
'MsgBox oPackage.Description, vbInformation, _
"Re-import Excel sheet."

'Clean up.
MsgBox ("Ran DTS Package")
Set oPackage = Nothing
Exit Sub
eh:
MsgBox Err.Description, vbCritical, _
"Error Running Package"

End Sub

View 3 Replies View Related

User Context That Package Executes Under ?

May 5, 2006

Hi There

I am trying to understand how to predict what user context a package will execute under, more specifically when it comes to operating system access.

For example we have a package that creates a flat file, during developement it was simply created on the C: drive of the users pc.

Now it must create the files on a remote server.

How do permissions to folders work is this case?

When you execute it in BIDS debug does it use the window account you logged onto the server as to connect to the remote folder ?

If so what happens when deployed to sql server and scheduled in a job? Does it use the domain account that the sql server agent account runs under ? Or will it use the credentials of the proxy account?

I am unclear in this scenario ? Obviously we need to grant the correct permissions on the remote server shared folder to the correct user, but i am not sure under what user account the package will be trying to create files on the remote server as ?

In a nutshell i need clarity on what user a package is executed as when running in a sql job ?

Anyone have a good link or the time to clarify this for me please.

Thanx

View 3 Replies View Related

Proc Hangs On Web But Executes In Query Analyzer

Jul 20, 2005

I'm currently updating one of our web sites and have encountered astrange problem. The page that is giving me the problem is written inASP and hits a SQL 2K DB. When I click submit I have 4 procs thatneed to be executed. I always get a sql server timeout error. Iopened up Profiler and traced the events. The page hangs on the lastproc called which is basically a select * where id = @id. If I runthe same proc that hangs in query analyzer, literally copy fromprofiler into query analyzer the proc runs no problem but when I'mhitting it from the web it hangs. The proc takes in 1 argument whichI see when I view the trace in profiler. The id getting passed to theproc is correct. I don't think this is a web problem because the COMobject that runs the last 2 procs works on other productionapplications with no problems. I was wondering if anyone has anysuggestions. I'm not a dba but would like to know what the problem isfor future reference. I pasted the proc below just for the hell ofit. FYI, I changed the name of the proc, table and columns forsecurity purposes.CREATE PROCEDURE [dbo].[spName]@TNum integerASSELECT M.*FROM tblName MWHERE (M.[idColumn] = @TNum)GOThanks in advance,Bob

View 3 Replies View Related

Strored Procedure Within SQL Transaction Executes Much Longer

Jul 20, 2005

Hi,I have stored procedure (MS SQL Server 2000) which operateson around 600 000 rows (SELECT, UPDATE, INSERT)and executes in 5 minutes,when I put it in SQL transaction it slows down to more than 5 hours (!!)I have to admit that it is not problem with data locks (beside thatprocedurenothing else is executed on db),It is not also problem with that exact procedure, other proceduresalso slow down heavily when wrapped by SQL transactionvery very seldom stored procedure within transaction executescomparably long that its copy without transactionI guess it could be MS SQL Server 2000 configuration/tuning problem.Any ideas ?Chris

View 1 Replies View Related

Snapshot Executes But Subscription Does Not Email To User

Sep 6, 2006

I have a problem with a report set up to execute a snapshot and subscription on day 1 of each month. On July 1, it ran and was emailed to the user; on 8/1 it created the snapshot but did not send to the user because of a user error in the subscription, so it was sent manually. the parameters issues were corrected and on 9/1 the snapshot executed but the subscription did not send. In the subscription window, the last good email of a snapshot was sent 7/1. So again 9/1 was sent manually. After fixing the parameters shouldn't this have emailed the snapshot correctly on 9/1?

Do I need to delete this subscription and create a new one to get it to send on 10/1 now?

any suggestions?

the set up is now verified to be identical to other reports which created a snapshot and emailed successfully, the only difference is the original problem with only the 7/1 subscription the only one you see when you look at the "subscription tab" for this report in Reporting services:

Description:Send e-mail to name.one@plife.com, name.two@plife.com

Trigger:SnapshotUpdated

Lastrun: 7/1/2006 7:00 AM

Mail Sent to:Mail sent to name.one@plife.com, name.two@plife.com

Snapshots successful






5/1/2006 7:00:02 AM



6/1/2006 7:00:03 AM



6/1/2006 8:26:31 AM



7/1/2006 7:00:07 AM



8/1/2006 7:00:24 AM



9/1/2006 7:00:19 AM




Logfile for "Ops Specialists/1035 Exchange Issue - Details (200407-R01)" report
Portion of log file:
ReportingServicesService!dbpolling!f!9/1/2006-07:00:04:: EventPolling processing item e869f577-b189-4e6a-a9be-37b61d737340
ReportingServicesService!dbpolling!13!9/1/2006-07:00:04:: EventPolling processing item 2b275311-0ee4-4cef-972d-86de48f4f360
ReportingServicesService!dbpolling!c!9/1/2006-07:00:04:: EventPolling processing item 3df3960a-ee28-4d5e-a46e-326ab5a0060d
ReportingServicesService!library!c!9/1/2006-07:00:04:: Schedule e11a00d3-56b6-46b3-b2d3-9e3156805be8 executed at 9/1/2006 7:00:04 AM.
ReportingServicesService!library!13!9/1/2006-07:00:04:: Schedule 177e9473-2c81-4152-a89f-137d25a556e1 executed at 9/1/2006 7:00:04 AM.
ReportingServicesService!library!4!9/1/2006-07:00:04:: Schedule 89071f26-435c-4cc7-bd9a-23907ef32b5c executed at 9/1/2006 7:00:04 AM.
ReportingServicesService!library!f!9/1/2006-07:00:04:: Schedule 3720d20c-460e-4549-9b57-c3cc97919f5f executed at 9/1/2006 7:00:04 AM.
ReportingServicesService!schedule!13!9/1/2006-07:00:04:: Updating report execution snapshot for report /Client Services/Ops Specialists/1035 Exchange Issue - Details (200407-R01)
ReportingServicesService!schedule!c!9/1/2006-07:00:04:: Updating report execution snapshot for report /Client Services/Ops Specialists/1035 Exchange Bridged - Details (200407-R01)
ReportingServicesService!schedule!f!9/1/2006-07:00:04:: Updating report execution snapshot for report /Client Services/Ops Specialists/Policy Counts (200401-R01)
ReportingServicesService!schedule!4!9/1/2006-07:00:04:: Updating report execution snapshot for report /Client Services/Inforce Admin/CAAB226 (200501-R03)
ReportingServicesService!dbpolling!d!9/1/2006-07:00:08:: EventPolling processing 4 more items. 8 Total items in internal queue.



View 8 Replies View Related

SSIS Package Executes Within BIDS But Not From A Stored Procedure

Feb 1, 2007

I have a SSIS package that contains a DTS 2000 package in it. The DTS 2000
package imports data into several tables from an ODBC data source. When I
execute the package through BIDS, no problems. Everything works great. I am
now trying to execute the SSIS package in my stored procedure & it gives me
the following error:
Error: 2007-01-30 11:54:24.06
Code: 0x00000000
Source: Populate IncrTables
Description: System.Runtime.InteropServices.COMException (0x80040427):
Execution was canceled by user.
at DTS.PackageClass.Execute()
at
Microsoft.SqlServer.Dts.Tasks.Exec80PackageTask.Exec80PackageTask.ExecuteThread()
End Error

I did a search for this & found KB 904796. It had the exact error message
but I don't believe my packages uses 2000 metadata services. Just to be
safe, I reinstalled the backward compatibility features & the DTS 2000 tools
on the server. That still did not fix anything. I found another forum that
suggested loading the DTS 2000 package internally, which I did & it did not
fix anything. I am using a password for the protection level so that is not
causing my issue. Does anyone else have any suggestions as to what I might be
able to try?

SQL 2005 Dev Ed SP1 & post SP1 hotfixes installed
Win 2k3 server
Thanks!
John

View 3 Replies View Related

How To Call A Stored Procedure Just After A TableAdapter's INSERT Command Executes

Feb 29, 2008

All-
Is there a way that I can embedd a call to a stored procedure into an existing INSERT section in a table adapter?
Say my objective is to call a stored procedure called personfill automatically RIGHT AFTER the TableAdapter inserts a row into the person table. One catch is that the stored procedure must be sent the value of unique identifier field person_id, which was created for the new person record automatically by the db. (If this is not possible to do, I might try using a TRIGGER in the person table.)
Below is the INSERT code of the TableAdapter. My guess is that if I could call a procedure, I would want to put the call between lines 12 and 13.
Your comments would be most appreciated!!!
-Kurt1 <InsertCommand>
2 <DbCommand CommandType="Text" ModifiedByUser="false">
3 <CommandText>INSERT INTO [person] ([family_id], [circle_id], [person_type_id], [last], [first], [username], [password]) VALUES (@family_id, @circle_id, @person_type_id, @last, @first, @username, @password)</CommandText>
4 <Parameters>
5 <Parameter AllowDbNull="false" AutogeneratedName="" DataSourceName="" DbType="Int16" Direction="Input" ParameterName="@family_id" Precision="0" ProviderType="SmallInt" Scale="0" Size="0" SourceColumn="family_id" SourceColumnNullMapping="false" SourceVersion="Current" />
6 <Parameter AllowDbNull="false" AutogeneratedName="" DataSourceName="" DbType="Int16" Direction="Input" ParameterName="@circle_id" Precision="0" ProviderType="SmallInt" Scale="0" Size="0" SourceColumn="circle_id" SourceColumnNullMapping="false" SourceVersion="Current" />
7 <Parameter AllowDbNull="false" AutogeneratedName="" DataSourceName="" DbType="Int16" Direction="Input" ParameterName="@person_type_id" Precision="0" ProviderType="SmallInt" Scale="0" Size="0" SourceColumn="person_type_id" SourceColumnNullMapping="false" SourceVersion="Current" />
8 <Parameter AllowDbNull="false" AutogeneratedName="" DataSourceName="" DbType="AnsiString" Direction="Input" ParameterName="@last" Precision="0" ProviderType="VarChar" Scale="0" Size="0" SourceColumn="last" SourceColumnNullMapping="false" SourceVersion="Current" />
9 <Parameter AllowDbNull="false" AutogeneratedName="" DataSourceName="" DbType="AnsiString" Direction="Input" ParameterName="@first" Precision="0" ProviderType="VarChar" Scale="0" Size="0" SourceColumn="first" SourceColumnNullMapping="false" SourceVersion="Current" />
10 <Parameter AllowDbNull="true" AutogeneratedName="" DataSourceName="" DbType="AnsiString" Direction="Input" ParameterName="@username" Precision="0" ProviderType="VarChar" Scale="0" Size="0" SourceColumn="username" SourceColumnNullMapping="false" SourceVersion="Current" />
11 <Parameter AllowDbNull="true" AutogeneratedName="" DataSourceName="" DbType="AnsiString" Direction="Input" ParameterName="@password" Precision="0" ProviderType="VarChar" Scale="0" Size="0" SourceColumn="password" SourceColumnNullMapping="false" SourceVersion="Current" />
12 </Parameters>
13 </DbCommand>
14 </InsertCommand>
15 <SelectCommand>
16 <DbCommand CommandType="Text" ModifiedByUser="true">
17
 

View 2 Replies View Related

Weird Problem: SP Executes Slowly, But Drop And Recreate Speeds It Up!

Feb 22, 2006

I have found an (encrypted) SP which takes ~20 seconds to run on one of our client DBs.

If I drop and recreate (or alter) the SP giving it the same contents it will run in ~1 second.

I need to know
1. why the sp started running so slowly
2. how to stop it happening again
3. how to fix it without resorting to drop/recreate (I can't exactly write a batch script to recreate all our sps every so often)

I have tried sp_updatestats and sp_recompile before running the sp to no avail...

anyone heard of a problem like this before?

cheers
H

View 11 Replies View Related

SQL Server 2012 :: Permissions For Executing Procedure Which Executes Other Procedures?

May 13, 2015

I have a stored procedure which executes about forty other stored procedures in several different databases. All of these other procedures truncate tables and insert new data into those tables selected from still other tables.

I want to run this top-level procedure using an account which can't do anything else.

Is there a simple way to give it all the permissions it needs without empowering it to do anything else?

View 0 Replies View Related

SQL DTS Query Using WHILE Statement Successfully Executes (only Updating 200 Of 1494 Records)

Jul 23, 2005

I am running a DTS Package.I have a temp table with 1494 records. I am inserting a 'Y' or'N'into a temp table #HasClaims.The TempTable name with the Provider Id's(PRPR_ID) is#TempFACETSNODupesThe @identityID is an identity field counting back from 1494 to 1I count back from the Max value of the identityid (1494) in the Whileloop until I get through all the records. The idea is to check for theexistance of a claims and authorization record and put a 'Y' or 'N'record in the temptable #HasClaims.This is running in the Execute SQL Task object of the DTS Package.The Package runs successfully but only inserts 200 rows into the newtemp table. There should be a row for each provider. Each time itruns, the number of rows it returns is different. Sometimes it is 205,then 185, then 210, before it completes the DTS package.Has anyone run into While looping problems within an Execute SQL taskin a DTS package(SQL 2000)like this--------------------------------------------------------------SELECT @identityID = MAX(IDENTITYID) FROM #TempFACETSNODupesWhile @identityID >= 1BEGIN@PRPRID is the placeholder for the PRPR_ID (Provider)SELECT @PRPRID = PRPR_ID FROM #TempFACETSNODupes WHERE IDENTITYID =@identityIDIF exists( SELECT CLCL_ID FROM dbo.CMC_CLCL_CLAIM CLCL WHERECLCL.PRPR_ID = @PRPRID)BEGININSERT INTO #HasClaims (PRPR_ID, HasClaims, IdentityID)VALUES( @PRPRID, 'Y', @identityID)ENDELSE INSERT INTO #HasClaims (PRPR_ID, HasClaims, IdentityID)VALUES( @PRPRID, 'N', @identityID)------------------------------------------------------------SELECT @identityID = @identityID - 1END

View 7 Replies View Related

SQL Statement Executes In Mngmt Studio, Doesn't In Integration Services

Oct 24, 2007



I have an T-SQL statement that runs in under 4 minutes on the Management Studio, and freezes forever in Integration Services. The statement ran fine before in both places, as well, but now I'm running on x64 OS with everything 64 bits including SQL.

The statement is this:


DECLARE @data datetime
set @data = DATEADD(DAY,-1,DATEADD(YEAR,-1, GETDATE()))

INSERT INTO TempDateModelo (Data) (SELECT Data FROM [tPosting Date] a WHERE a.Data>=@data)

INSERT INTO fModelo([Item Department], [Centro Custo], [Posting Date]) (Select b.[Item Department], c.[Centro Custo], d.[Data] FROM [mItem Department] b, [mCentrosCusto] c, [TempDateModelo] d)

UPDATE fModelo SET [Vendas MM Anterior]=
(SELECT SUM(b.[Custo Vendas]) FROM fValues b WHERE (b.[Posting Date] BETWEEN DATEADD(YEAR,-1,DATEADD(DAY,-27,fModelo.[Posting Date])) AND DATEADD(YEAR,-1,fModelo.[Posting Date])) AND b.[Item Department]=fModelo.[Item Department] AND b.[Centro Custo]=fModelo.[Centro Custo])

UPDATE fModelo SET [Vendas MM Posterior]=
(SELECT SUM(b.[Custo Vendas]) FROM fValues b WHERE (b.[Posting Date] BETWEEN DATEADD(YEAR,-1,fModelo.[Posting Date]) AND DATEADD(YEAR,-1,DATEADD(DAY,27,fModelo.[Posting Date]))) AND b.[Item Department]=fModelo.[Item Department] AND b.[Centro Custo]=fModelo.[Centro Custo])

UPDATE fModelo SET Dia = DATEPART(DAY, [Posting Date]), Mes = MONTH([Posting Date])

View 2 Replies View Related

How To Retrieve The Result From A Stored Procedure That Executes A Dynamically Built Up Sql Query?

Apr 2, 2008

We have a sort of complex user structure in the sense that depending on the type of user the data resides in different tables. Therefor I needed a stored procedure that finds out what table to look for a certain column in. Below is such a stored procedure and it works like it should but my problem is that I don't know how to retrieve the result (which should be a string so can't use RETURN).

I've tried using an OUTPUT variable but since I just run EXEC (@statement) in the end I can't really set an output variable the common way (as in EXEC @outputVariable = PMC_User_GetUserValue(arg1, arg2..)) or can I?

I have also tried to use SELECT to catch the result somehow but no luck and Google didn't help either so now I'm hoping for one of you... Notice that you don't have to bother about much of the code except for the end of it where I want it to return somehow or figure out a way to call this stored procedure and retrieve the result.

Thanks in advance
ripern

-- Retrieves the value of column @columnName for credential id @credID
ALTER PROCEDURE [dbo].[PMC_User_GetUserValue]
@credID int,
@columnName nvarchar(50)
AS

DECLARE @userDataTable nvarchar(50)
DECLARE @userDataID int
DECLARE @statement nvarchar(500)
SET @statement = ' '

SET @userDataID =
(SELECT PMC_UserMapping.fk_userDataID
FROM PMC_UserMapping
INNER JOIN PMC_User ON PMC_UserMapping.fk_user_id = PMC_User.id
WHERE PMC_User.fk_credentials_id = @credID)

SET @userDataTable =
(SELECT PMC_UserType.userDataTable
FROM PMC_UserType
INNER JOIN PMC_UserMapping ON PMC_UserType.id = PMC_UserMapping.fk_usertype_id
INNER JOIN PMC_User ON PMC_UserMapping.fk_user_id = PMC_User.id
WHERE PMC_User.fk_credentials_id = @credID)

SET @statement = 'SELECT ' + @columnName + ' AS columnValue FROM ' + @userDataTable + ' WHERE id=' + convert(nvarchar, @userDataID)

-- Checks whether the given column name exists in the user data table for the given credential id.
IF EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME=@userDataTable AND COLUMN_NAME=@columnName )
BEGIN
EXEC (@statement)
END

View 12 Replies View Related

Send Email If Packages Executes For Longer Than A Secified Amount Of Time

Nov 15, 2007



Is there a way ( using an included SSIS task rather than coding a script task) to detect whether a package has run longer than a specified period of time?

So I can send an email to operators notifying them that a job is taking longer than usual.

Thanks

View 12 Replies View Related

Same Statement Executes 10 Times Faster As Raw Sql In Query Analyzer Then In A Stored Proc

Aug 15, 2007



Hi,


I apologize for the long post but I am trying to give as much information as I can about the steps I've taken to troubleshoot this.


We have a stored procedure that builds a sql statement and executes it using the Execute command. When I execute the stored procedure through query analyzer it takes close to 5 seconds to execute. When I print out the exact same statement and execute it directly in query analyzer as "raw sql", it takes 0.5 seconds - meaning it takes 10 times longer for the code to execute in the stored proc. I altered the stored proc to execute the printed sql instead of building but it still takes the full 5 seconds and there were no changes in the execution plan. This makes me confident that the issue is not caused by the dynamic sql. I've used with recompile to make sure that the stored procedure caches the most recent execution plan. When I compare the execution plans, the stored proc uses a nested loop whereas the raw sql statement uses a hash join. Seeing that, I added the hash hint to the stored proc and doing so brought down the execution time down from 5 secs to 2 secs but still the raw sql statement uses a clustered index whereas the stored proc uses a non-clustered index and that makes the statement 4 times slower. This proves how efficient clustered indexes are over non-clustered ones, but it doesn't help me since, as far as I know, I can't force SQL Server to use the clustered index.


Does anyone know why sql server is generating such an inefficient execution plan for the stored proc compared to the execution plan that it generates when executing the raw sql statement? The only thing I can think of is that some stats are not updated and that somehow throws off the stored proc. But then again, shouldn't it affect the raw sql statement?


Thank you,


Michael Tzoanos

View 4 Replies View Related

Query Executes Faster In Grid Mode Than In Text Mode!!

Mar 9, 2000

Hello,everyone!!

There is a query which when executed in the grid mode(ctrl+d) takes approx 0.02 seconds(about 21,000
rows) But when I execute in the text mode, it takes about 0.40 seconds!!
Why is this difference?
Also, when the records from this table are read from a VB application, they are equally slow (as in the text mode!)
Why is it so slow on the text mode & relatively faster in the grid mode?
Has anyone got any idea on ‘Firehose’ style cursor ?(which may speed up access of data in the VB application)

Rgds,
Adie

View 1 Replies View Related

Package Executes On Test Database But Not In Production Database

Aug 24, 2006

hi!

I am able to run the package successfuly in test database. but not in production database. It throughs up error saying

Description: Unable to load the package as XML because of package does not have a valid XML format. A specific XML parser error will be posted.
Description: Failed to open package file "D:\TAHOE\APPS\SSISPackages\Integration Services Packages\ArchiveMain.dtsx" due to error 0x80070015 "The device is not ready.". This happens when loading a package and the file cannot be opened or loaded c
orrectly into the XML document. This can be the result of either providing an incorrect file name was specified when calling LoadPackage or the XML file was specified and has an incorrect format.
End Error
Could not load package "D:\TAHOE\APPS\SSISPackages\Integration Services Packages\ArchiveMain.dtsx" because of error 0xC0011002.
Description: Failed to open package file "D:\TAHOE\APPS\SSISPackages\Integration Services Packages\ArchiveMain.dtsx" due to error 0x80070015 "The device is not ready.". This happens when loading a package and the file cannot be opened or loaded corr
ectly into the XML document. This can be the result of either providing an incorrect file name was specified when calling LoadPackage or the XML file was specified and has an incorrect format.

what is the problem here....

JAs

View 3 Replies View Related

CLR-Based Trigger? Recursive Trigger? Common Table Expression?

Nov 14, 2006

Hey,

I'm new to this whole SQL Server 2005 thing as well as database design and I've read up on various ways I can integrate business constraints into my database. I'm not sure which way applies to me, but I could use a helping hand in the right direction.

A quick explanation of the various tables I'm dealing with:
WBS - the Work Breakdown Structure, for example: A - Widget 1, AA - Widget 1 Subsystem 1, and etc.
Impacts - the Risk or Opportunity impacts for the weights of a part/assembly. (See Assemblies have Impacts below)
Allocations - the review of the product in question, say Widget 1, in terms of various weight totals, including all parts. Example - September allocation, Initial Demo allocation, etc. Mostly used for weight history and trending
Parts - There are hundreds of Parts which will eventually lead to thousands. Each part has a WBS element. [Seems redundant, but parts are managed in-house, and WBS elements are cross-company and issued by the Government]
Parts have Allocations - For weight history and trending (see Allocations). Example, Nut 17 can have a September 1st allocation, a September 5th allocation, etc.
Assemblies - Parts are assemblies by themselves and can belong to multiple assemblies. Now, there can be multiple parts on a product, say, an unmanned ground vehicle (UGV), and so those parts can belong to a higher "assembly" [For example, there can be 3 Nut 17's (lower assembly) on Widget 1 Subsystem 2 (higher assembly) and 4 more on Widget 1 Subsystem 5, etc.]. What I'm concerned about is ensuring that the weight roll-ups are accurate for all of the assemblies.
Assemblies have Impacts - There is a risk and opportunity impact setup modeled into this design to allow for a risk or opportunity to be marked on a per-assembly level. That's all this table represents.

A part is allocated a weight and then assigned to an assembly. The Assemblies table holds this hierarchical information - the lower assembly and the higher one, both of which are Parts entries in the [Parts have Allocations] table.

Therefore, to ensure proper weight roll ups in the [Parts have Allocations] table on a per part-basis, I would like to check for any inserts, updates, deletes on both the [Parts have Allocations] table as well as the [Assemblies] table and then re-calculate the weight roll up for every assembly. Now, I'm not sure if this is a huge performance hog, but I do need to keep all the information as up-to-date and as accurate as possible. As such, I'm not sure which method is even correct, although it seems an AFTER DML trigger is in order (from what I've gathered thus far). Keep in mind, this trigger needs to go through and check every WBS or Part and then go through and check all of it's associated assemblies and then ensure the weights are correct by re-summing the weights listed.

If you need the design or create script (table layout), please let me know.

Thanks.

View 4 Replies View Related

Trouble With Update Trigger Modifying Table Which Fired Trigger

Jul 20, 2005

Are there any limitations or gotchas to updating the same table whichfired a trigger from within the trigger?Some example code below. Hmmm.... This example seems to be workingfine so it must be something with my specific schema/code. We'reworking on running a SQL trace but if anybody has any input, fireaway.Thanks!create table x(Id int,Account varchar(25),Info int)GOinsert into x values ( 1, 'Smith', 15);insert into x values ( 2, 'SmithX', 25);/* Update trigger tu_x for table x */create trigger tu_xon xfor updateasbegindeclare @TriggerRowCount intset @TriggerRowCount = @@ROWCOUNTif ( @TriggerRowCount = 0 )returnif ( @TriggerRowCount > 1 )beginraiserror( 'tu_x: @@ROWCOUNT[%d] Trigger does not handle @@ROWCOUNT[color=blue]> 1 !', 17, 127, @TriggerRowCount) with seterror, nowait[/color]returnendupdate xsetAccount = left( i.Account, 24) + 'X',Info = i.Infofrom deleted, inserted iwhere x.Account = left( deleted.Account, 24) + 'X'endupdate x set Account = 'Blair', Info = 999 where Account = 'Smith'

View 1 Replies View Related

Generic Audit Trigger CLR C#(Works When The Trigger Is Attached To Any Table)

Dec 5, 2006

This Audit Trigger is Generic (i.e. non-"Table Specific") attach it to any tabel and it should work. Be sure and create the 'Audit' table first though.

The following code write audit entries to a Table called
'Audit'
with columns
'ActionType' //varchar
'TableName' //varchar
'PK' //varchar
'FieldName' //varchar
'OldValue' //varchar
'NewValue' //varchar
'ChangeDateTime' //datetime
'ChangeBy' //varchar

using System;
using System.Data;
using System.Data.SqlClient;
using Microsoft.SqlServer.Server;

public partial class Triggers
{
//A Generic Trigger for Insert, Update and Delete Actions on any Table
[Microsoft.SqlServer.Server.SqlTrigger(Name = "AuditTrigger", Event = "FOR INSERT, UPDATE, DELETE")]

public static void AuditTrigger()
{
SqlTriggerContext tcontext = SqlContext.TriggerContext; //Trigger Context
string TName; //Where we store the Altered Table's Name
string User; //Where we will store the Database Username
DataRow iRow; //DataRow to hold the inserted values
DataRow dRow; //DataRow to how the deleted/overwritten values
DataRow aRow; //Audit DataRow to build our Audit entry with
string PKString; //Will temporarily store the Primary Key Column Names and Values here
using (SqlConnection conn = new SqlConnection("context connection=true"))//Our Connection
{
conn.Open();//Open the Connection
//Build the AuditAdapter and Mathcing Table
SqlDataAdapter AuditAdapter = new SqlDataAdapter("SELECT * FROM Audit WHERE 1=0", conn);
DataTable AuditTable = new DataTable();
AuditAdapter.FillSchema(AuditTable, SchemaType.Source);
SqlCommandBuilder AuditCommandBuilder = new SqlCommandBuilder(AuditAdapter);//Populates the Insert command for us
//Get the inserted values
SqlDataAdapter Loader = new SqlDataAdapter("SELECT * from INSERTED", conn);
DataTable inserted = new DataTable();
Loader.Fill(inserted);
//Get the deleted and/or overwritten values
Loader.SelectCommand.CommandText = "SELECT * from DELETED";
DataTable deleted = new DataTable();
Loader.Fill(deleted);
//Retrieve the Name of the Table that currently has a lock from the executing command(i.e. the one that caused this trigger to fire)
SqlCommand cmd = new SqlCommand("SELECT object_name(resource_associated_entity_id) FROM
ys.dm_tran_locks WHERE request_session_id = @@spid and resource_type = 'OBJECT'", conn);
TName = cmd.ExecuteScalar().ToString();
//Retrieve the UserName of the current Database User
SqlCommand curUserCommand = new SqlCommand("SELECT system_user", conn);
User = curUserCommand.ExecuteScalar().ToString();
//Adapted the following command from a T-SQL audit trigger by Nigel Rivett
//http://www.nigelrivett.net/AuditTrailTrigger.html
SqlDataAdapter PKTableAdapter = new SqlDataAdapter(@"SELECT c.COLUMN_NAME
from INFORMATION_SCHEMA.TABLE_CONSTRAINTS pk ,
INFORMATION_SCHEMA.KEY_COLUMN_USAGE c
where pk.TABLE_NAME = '" + TName + @"'
and CONSTRAINT_TYPE = 'PRIMARY KEY'
and c.TABLE_NAME = pk.TABLE_NAME
and c.CONSTRAINT_NAME = pk.CONSTRAINT_NAME", conn);
DataTable PKTable = new DataTable();
PKTableAdapter.Fill(PKTable);

switch (tcontext.TriggerAction)//Switch on the Action occuring on the Table
{
case TriggerAction.Update:
iRow = inserted.Rows[0];//Get the inserted values in row form
dRow = deleted.Rows[0];//Get the overwritten values in row form
PKString = PKStringBuilder(PKTable, iRow);//the the Primary Keys and There values as a string
foreach (DataColumn column in inserted.Columns)//Walk through all possible Table Columns
{
if (!iRow[column.Ordinal].Equals(dRow[column.Ordinal]))//If value changed
{
//Build an Audit Entry
aRow = AuditTable.NewRow();
aRow["ActionType"] = "U";//U for Update
aRow["TableName"] = TName;
aRow["PK"] = PKString;
aRow["FieldName"] = column.ColumnName;
aRow["OldValue"] = dRow[column.Ordinal].ToString();
aRow["NewValue"] = iRow[column.Ordinal].ToString();
aRow["ChangeDateTime"] = DateTime.Now.ToString();
aRow["ChangedBy"] = User;
AuditTable.Rows.InsertAt(aRow, 0);//Insert the entry
}
}
break;
case TriggerAction.Insert:
iRow = inserted.Rows[0];
PKString = PKStringBuilder(PKTable, iRow);
foreach (DataColumn column in inserted.Columns)
{
//Build an Audit Entry
aRow = AuditTable.NewRow();
aRow["ActionType"] = "I";//I for Insert
aRow["TableName"] = TName;
aRow["PK"] = PKString;
aRow["FieldName"] = column.ColumnName;
aRow["OldValue"] = null;
aRow["NewValue"] = iRow[column.Ordinal].ToString();
aRow["ChangeDateTime"] = DateTime.Now.ToString();
aRow["ChangedBy"] = User;
AuditTable.Rows.InsertAt(aRow, 0);//Insert the Entry
}
break;
case TriggerAction.Delete:
dRow = deleted.Rows[0];
PKString = PKStringBuilder(PKTable, dRow);
foreach (DataColumn column in inserted.Columns)
{
//Build and Audit Entry
aRow = AuditTable.NewRow();
aRow["ActionType"] = "D";//D for Delete
aRow["TableName"] = TName;
aRow["PK"] = PKString;
aRow["FieldName"] = column.ColumnName;
aRow["OldValue"] = dRow[column.Ordinal].ToString();
aRow["NewValue"] = null;
aRow["ChangeDateTime"] = DateTime.Now.ToString();
aRow["ChangedBy"] = User;
AuditTable.Rows.InsertAt(aRow, 0);//Insert the Entry
}
break;
default:
//Do Nothing
break;
}
AuditAdapter.Update(AuditTable);//Write all Audit Entries back to AuditTable
conn.Close(); //Close the Connection
}
}


//Helper function that takes a Table of the Primary Key Column Names and the modified rows Values
//and builds a string of the form "<PKColumn1Name=Value1>,PKColumn2Name=Value2>,......"
public static string PKStringBuilder(DataTable primaryKeysTable, DataRow valuesDataRow)
{
string temp = String.Empty;
foreach (DataRow kColumn in primaryKeysTable.Rows)//for all Primary Keys of the Table that is being changed
{
temp = String.Concat(temp, String.Concat("<", kColumn[0].ToString(), "=", valuesDataRow[kColumn[0].ToString)].ToString(), ">,"));
}
return temp;
}
}

The trick was getting the Table Name and the Primary Key Columns.
I hope this code is found useful.

Comments and Suggestion will be much appreciated.

View 16 Replies View Related

Trigger - Require Help For Updating A Trigger Following An INSERT On Another Table

Oct 30, 2007

Table 1





First_Name

Middle_Name

Surname


John

Ian

Lennon


Mike

Buffalo

Tyson


Tom

Finney

Jones

Table 2




ID

F

M

S

DOB


1

Athony

Harold

Wilson

24/4/67


2

Margaret

Betty

Thathcer

1/1/1808


3

John

Ian

Lennon

2/2/1979


4

Mike

Buffalo

Tyson

3/4/04


5

Tom

Finney

Jones

1/1/2000


I want to be able to create a trigger that updates table 2 when a row is inserted into table 1. However I€™m not sure how to increment the ID in table 2 or to update only the row that has been inserted.

View 17 Replies View Related

Trigger - Require Help For Updating A Trigger Following An INSERT On Another Table

Feb 5, 2008

A





ID

Name


1

Joe


2

Fred


3

Ian


4

Bill


B





ID


1


4

I want to be able to create a trigger so that when a row is inserted into table A by a specific user then the ID will appear in table B. Is it possible to find out the login id of the user inserting a row?

I believe the trigger should look something like this:

create trigger test_trigger
on a
for insert
as
insert into b(ID)

select i.id
from inserted i
where
--specific USER

View 9 Replies View Related

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

Mar 18, 2008

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

View 3 Replies View Related

Modifing The Row That Invokes A Trigger From Within That Trigger

Jul 23, 2005

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

View 4 Replies View Related

Disabilitazione Trigger [DISABLE TRIGGER]

Jul 20, 2005

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

View 4 Replies View Related

Update Trigger Behaviour W/o A Trigger.

May 30, 2008

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

View 3 Replies View Related







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