Too Busy To Implement A Trigger? Nor A Conditional Update Query?

Dec 20, 2004

Hi:

In a very busy SQL2000 enterprise edition server with 8GB memory and 6 cpus sp3, I could not install a update trigger, unless all the appl connections are dropped. For this 24 HR running svr, could do it.

then I try to run a query as follows:

if exists (select rfABC.* A
from rfABC inner join remoteSvr.XYZDB.dbo.vwIP L
on A.Address = L.address and
A.metro <> L.metro
begin
print ' ---- Yes metroID <> LAMetro, start job exec.... -----'

insert into tempCatchMetroIDGPRS
select rfABC.*, metro, getdate()
from rfABC inner join remoteSvr.XYZDB.dbo.vwIP L on rfABC.Address = L.address and rfABC.metro <> L.metro

update rfABC A
set A.metro = L.metro
from rfABC A inner join remoteSvr.XYZDB.dbo.vwIP L on A.Address = L.address and A.metro <> L.metro
end
else
begin
print ' ---- no metroID <> LAMetro, skip job exec.... -----'
end

------------------------------
this query hang there could not execute. When I took off the if ... else condition, it run with like 0 second. Wondered if a 'busy' (which updates the IP address continueously) could cause above issues...

thanks
David

View 4 Replies


ADVERTISEMENT

Need Assistance On Conditional Update Trigger

Jul 3, 2006

I need some help here in creating a conditional update trigger. The purpose of this trigger would check to see if a contact already exist in the database on an insert and update only the fields that are null.

So How would I compare each field from the CONTACTS Table against my INSERTED Table?

Inserted.FirstName (COMPARE) Contacts.Firstname

Inserted.LastName (COMPARE) Contacts.LastName

Inserted.Email (COMPARE) Contacts.Email



I will be using the email address as the check for the duplicate record and if a duplicate is found... Instead of not allowing the insert I want to compare the existing record and update any fields that are NULL in Contacts with Inserted.

I have no idea on how to compare all of the fields.



Any help appreciated.

sadler_david@yahoo.com

View 1 Replies View Related

Microsoft Visual Studio Is Busy [caused By Refactor Trigger]

Dec 27, 2007

I'm now getting this with great regularity. Dell PWS390,2gig,Big HD,experienced user C++...Refactor recently installed although I do not use it.
CLEARLY, the hang comes when one highlites a line and then cursors down to highlight additional lines...I believe this invokes refactoring --- while pre-refactoring install would get a hang occasionally, I now get one frequently. I am uninstalling refactor....

View 1 Replies View Related

Update Trigger - Update Query

Jul 20, 2005

Hi there,I'm a little stuck and would like some helpI need to create an update trigger which will run an update query onanother table.However, What I need to do is update the other table with the changedrecord value from the table which has the trigger.Can someone please show me how this is done please??I can write both queries, but am unsure as to how to get the value ofthe changed record for use in my trigger???Please helpM3ckon*** Sent via Developersdex http://www.developersdex.com ***Don't just participate in USENET...get rewarded for it!

View 1 Replies View Related

Implement Logic For Update Or Insert

May 1, 2006

I have a stored procedure that I need to either perform an update if a record exists or an insert if the record doesn't exist.

Here is my procedure:

CREATE PROCEDURE dbo.Insert_Temp_ContactInfo

@sessionid varchar(50),
@FirstName varchar(50),
@LastName varchar(50),
@SchoolName varchar(50),
@address varchar(50),
@City varchar(50),
@State int,
@Zip varchar(5),
@Phone varchar(10),
@Email varchar(50),
@CurrentCustomer varchar(3),
@ImplementationType int,
@ProductType int = null,
@Comment varchar(500)

AS

--check if a current record exists

SET NOCOUNT ON

SELECT FirstName, LastName, SchoolName, Address, City, State, Zip, Phone, Email, CurrentCustomer, ImplementationType, ProductType, Comment
FROM dbo.Temp_ContactInfo
WHERE sessionid = @sessionid


SET NOCOUNT OFF


--if exists update the record

UPDATE dbo.Temp_ContactInfo
SET
FirstName = @FirstName,
LastName = @LastName,
SchoolName = @SchoolName,
Address = @address,
City = @City,
State = @State,
Zip = @Zip,
Phone = @Phone,
Email = @Email,
CurrentCustomer = @CurrentCustomer,
ImplementationType = @ImplementationType,
ProductType = @ProductType,
Comment = @Comment
WHERE sessionid = @sessionid

--if the record does not exist, then insert a new record

INSERT INTO dbo.Temp_ContactInfo (sessionid, FirstName, LastName, SchoolName, address, City, State, Zip, Phone, Email, CurrentCustomer, ImplementationType, ProductType, Comment)
VALUES (@sessionid, @FirstName, @LastName, @SchoolName, @address, @City, @State, @Zip, @Phone, @Email, @CurrentCustomer, @ImplementationType, @ProductType, @Comment)

GO

I think I can use an if statement. Can anyone help me out with this?

Thanks.

View 3 Replies View Related

How To Implement T-SQL Update Command Using Special Characters

Mar 24, 2008

Hi!
I wanted to execute an update command in T-SQL using some special characters like single quote ('). when i try with this it fails to accept the command. For example the text which i wanted to update is something like this "<Choice index="3" value="Don't know"/>", here i have a single quote('), less/greater than signs (<>), double quotes and forward slash (/). when i try with this type of text it fails to update, the field data type is NChar. I need help on how to successfully execute with this type of data.

Need help.


Thanks In Advance

Devloper
Anil Kumar Dwivedi

View 8 Replies View Related

Automatically Trigger A Sum From One Table To Another Upon Update/insert Query

Jul 12, 2005

I'm trying to update (increment)
Company.SumtotalLogons
from CompanyUsers.NumberOfLogons
where CompanyUsers.CompanyID = Company.CompanyID

I'd like to either write a formula (if it is even possible to fire a formula from one table update/insert to increment a field in another table), or a stored procedure that triggers an auto update/append into Company.SumTotalLogons

I know this is possible in access, so i'm wondering how to go about it in ms-sql?

any ideas?

View 1 Replies View Related

Conditional Trigger

Jul 17, 2006

I have a trigger that updates values in a table when col2 is updated by a stored procedure.

I'd like to make this a conditonal trigger to prevent negative values from being inserted in the table. I'm not familiar with the syntax of triggers enough to get this to work and I've search for a reference with no luck.

Here's the current trigger code:


Code:

FOR INSERT, UPDATE
AS
UPDATE table1
SET col4= col1 - col2 - col3



I need to evaulate (col1 - col2 - col3) to see if it's less than zero. If it is, I want to set col4=0.

This is what I've tried, but it doesn't work. Any help is appreciated:


Code:

FOR INSERT, UPDATE
AS
select col1, col2, col3 from table1
if (col1 - col2 - col3) < 0
UPDATE table1
SET col4 = 0
else
UPDATE table1
SET col4= col1 - col2 - col3

View 3 Replies View Related

Conditional Trigger

Feb 22, 2008

Hello,

I have a situation where I'd like to fire a trigger only when certain conditions are met for data that's inserted into it's parent table.

Here is what I'm working with -

The PropertyScenarioIndex table currently contains this data:
PropertyID ScenarioType ScenarioID
1732 financing 1
1732 financing 2
1732 financing 3
1732 income_expense 1
1732 income_expense 2

The PropertyScenarioIndex table has a trigger on it (the one that needs to be made conditional) whose purpose is to automatically insert rows into another table called IncomeAndExpenseData to make entries easier for the user in that table. Here is the trigger:




Code Snippet

CREATE TRIGGER addstandardIncomeAndExpenserows ON PropertyScenarioIndex
AFTER INSERT
AS
insert into IncomeAndExpenseData
select
properytID = t1.propertyID,
scenarioID = t1.scenarioID,
itemID = t2.itemID,
itemvalue = null,
monthitemvalue = null
from PropertyScenarioIndex t1
cross join IncomeAndExpenseCodes t2
where
t1.propertyID+t1.scenarioID in (select propertyID+scenarioID from Inserted)
and t2.standarditem = 1
With the trigger as it is above, when the user tries to enter the following into PropertyScenarioIndex:
PropertyID ScenarioType ScenarioID
1732 income_expense 3
an error message appears that says Violation of PRIMARY KEY constraint 'PK_IncomeExpenseData'. Cannot insert duplicate key in object 'IncomeExpenseData'.

Is there some way to include code in the trigger that makes it fire only when the data inserted into the PropertyScenarioIndex table has a ScenarioType of 'income_expense'?

Note: in the where statement of the trigger above I have also tried this:




Code Snippet

where
t1.propertyID+t1.scenarioID in (select propertyID+scenarioID from Inserted where scenariotype = 'income_expense')but got the same error message as noted above.

Thanks, Knot

P.S. The primary keys in the PropertyScenarioIndex table are PropertyID, ScenarioType, ScenarioID and the primary keys in the IncomeExpenseData table are called PropertyID, ScenarioID, ItemID.

View 10 Replies View Related

'Timeout Expired' Error Due To Long Query Or Busy Server?

May 2, 2008

We have been bothered with this problem for a while.  Usually I happens in the early moring.  Later on after the error is gone on auser, the error never happens again on any user for the day.  Is this a web Server problem or an aspx.vb coding error? Thanks,Jeffrey 
Server Error in '/SSSSS' Application.


Timeout expired.  The timeout period elapsed prior to completion of the operation or the server is not responding.
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: Timeout expired.  The timeout period elapsed prior to completion of the operation or the server is not responding.Source Error:



Line 270: oDBCommand.Connection.Open()
Line 271:
Line 272: Dim myReader As SqlDataReader _
Line 273: = oDBCommand.ExecuteReader(CommandBehavior.CloseConnection)
Line 274:Source File: E:SSSSSScheduling.aspx.vb    Line: 272 Stack Trace:



[SqlException (0x80131904): Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding.]
System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection) +862234
System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection) +739110
System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj) +188
System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj) +1956
System.Data.SqlClient.SqlDataReader.ConsumeMetaData() +31
System.Data.SqlClient.SqlDataReader.get_MetaData() +62
System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString) +297
System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async) +903
System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, DbAsyncResult result) +132
System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method) +32
System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method) +122
System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior) +62
Soma.Scheduling.GetNextAutoAppointment() in E:SSSSSAScheduling.aspx.vb:272
Soma.Scheduling.Page_Load(Object sender, EventArgs e) in E:SSSSSScheduling.aspx.vb:61
System.Web.UI.Control.OnLoad(EventArgs e) +99
System.Web.UI.Control.LoadRecursive() +47
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1061

View 7 Replies View Related

How To Implement Alter Database Implement Restrictions On SQL2K ?

Dec 28, 2007

Hi Guyz

it is taken from SQL2K5 SP2 readme.txt. Anyone have idea what to do to implement this ?
Our sp2 is failing. we suspect the above problem and researching it.we are running on default instance of SQL2K5 on win2003 ent sp2

"When you apply SP2, Setup upgrades system databases. If you have implemented restrictions on the ALTER DATABASE syntax, this upgrade may fail. Restrictions to ALTER DATABASE may include the following:

Explicitly denying the ALTER DATABASE statement.


A data definition language (DDL) trigger on ALTER DATABASE that rolls back the transaction containing the ALTER DATABASE statement.


If you have restrictions on ALTER DATABASE, and Setup fails to upgrade system databases to SP2, you must disable these restrictions and then re-run Setup."

thanks in advance.

View 4 Replies View Related

Conditional Delete Trigger

Feb 15, 2005

On the database that I am maintaining we are having some data integrity issues between our Logon table and another sub table that stores the LogonId.

The best solution would be to put in a foreign key, but that is going to require a lot of work and a lot of code changes for the entire system. This is what we plan to do, but this is not a quick fix. We need something that can be implemented quickly.

The easiest and quickest fix is to check this sub table to see if the LogonId is in the sub table and the row is marked as Active or Working. If it is then we will abort the deletion and raise an error. Otherwise the delete should happen normally.

Is aborting the deletion as simple as :

<code>
Delete From deleted
Where LogonId = @myId
</code>

Or am I missing something?

Thanks for the help,
Tim

View 2 Replies View Related

Help With Performance On A Conditional Trigger

Feb 27, 2004

I have a pretty massive conditional trigger. If there is another way of going about this, please let me know. But I'm populating a temp table with records and based on many conditions, I am transforming this data to another table in a corrected format. These conditions I am using reference the final table in many ways, and this seems to become slower and slower as the final table grows larger.

Take a look and see if you can help me please.

View 2 Replies View Related

Conditional Insert Trigger

Mar 14, 2006

Is there any way to create a "Conditional Insert Trigger"
My Scenario is this;
When a user adds an email address to the database, I want to look to see if the email address is like '%@acme-holdings%' and if it is then to change the value to 'Not allowed', otherwise to leave it alone and go ahead with inserting the original email address

TIA

ICW

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

Conditional Update

Feb 21, 2006

Hello all, my update statement works as expected, but lacks some conditional logic. How can I change the statement to not decrement qtyonhand if the quantity is 0? Additionally, I would need to return to the calling application something that would allow me to populate a label with a message to the user.. How can that be accomplished?
Here is my sproc:CREATE PROCEDURE [webuser].[cssp_removeItem]
@lblID int
AS
Update cstb_inventoryset qtyonhand = qtyonhand -1where Id = @lblIDGO
Here is my app code:
Try
Dim cmd As SqlCommand = cn.CreateCommand
cmd = New SqlCommand("cssp_removeItem", cn)
cmd.CommandType = CommandType.StoredProcedure
With cmd
cmd.Parameters.Add("@lblId", SqlDbType.Int).Value = lblId.Text
End With
If Not cn.State = ConnectionState.Open Then
cn.Open()
End If
cmd.ExecuteNonQuery()
Catch ex As Exception
Response.Write(ex.ToString)
Finally
If Not cn.State = ConnectionState.Closed Then
cn.Close()
cn = Nothing
End If
 

View 6 Replies View Related

Using Stored Procedure To Implement Multi-keywords Query

Mar 28, 2000

Hello,

I am greener in using SQL Server 7.0. I created a stored procedure named usp_Test (please see the following codes for reference). It worked fine when passed through a single keyword into it (for example usp_Test 'Satellite'), but it did not return the query results what I wanted when passed through multiple keywords into it (for example usp_Test 'Satellite Remote'). In fact, it returned nothing but the column names specified in SELECT statement. Below is the sample of procedure how it looks like. Where am I wrong? Any idea?

CREATE PROCEDURE usp_Test
@strKeywords varchar(50)
AS

DECLARE @DelimiterPos integer
DECLARE @Delimiter char(1)
DECLARE @strWHERE varchar(1000)

SET @DelimiterPos = 0
SET @Delimiter = CHAR(32)
SET @strWHERE =""
SET @strKeywords = RTRIM(LTRIM(@strKeywords))

SET @DelimiterPos = CHARINDEX(@Delimiter,@strKeywords,1)

IF @DelimiterPos > 0
BEGIN
WHILE (@DelimiterPos > 0)
BEGIN
IF LEN(@strWHERE) > 0
BEGIN
SET @strWHERE = @strWHERE + " AND tblClips.Title Like %" + LEFT(@strKeywords,@DelimiterPos - 1)+ "%" + CHAR(13)
END
ELSE
BEGIN
SET @strWHERE = @strWHERE + "%" + LEFT(@strKeywords,@DelimiterPos - 1) + "%" + CHAR(13)
END
SET @strKeywords = LTRIM(RIGHT(@strKeywords, LEN(@strKeywords) - @DelimiterPos))
SET @DelimiterPos = CHARINDEX(@Delimiter, @strKeywords, 1)
IF @DelimiterPos > 0
BEGIN
CONTINUE
END
ELSE
IF LEN(@strKeywords) > 0
BEGIN
SET @strWHERE = @strWHERE + " AND tblClips.Title Like %" + @strKeywords + "%" + CHAR(13)
BREAK
END
END
END
ELSE
BEGIN
SET @strWHERE = @strWHERE + "%" + @strKeywords + "%"
END
PRINT 'WHERE tblClips.Title Like ' + @strWHERE
SELECT tblClips.Title,tblTapes.ClassificationNo,tblTapes. Inventory
FROM tblClips INNER JOIN (tblClipTape
INNER JOIN tblTapes
ON tblClipTape.fkTapeID = tblTapes.TapeID)
ON tblClips.ClipID = tblClipTape.fkClipID
WHERE tblClips.Title LIKE @strWHERE

Thank you very much in advance.
Changbaoi

View 1 Replies View Related

Update Variable After A Conditional Split

Oct 13, 2006

I have a Variable called - UpdateIDs.
I would like to create a conditional split on id's that have no responses and id's that have responses.
The idea is. There is a whole bunch of tables that can be updated if the foreign key is in the no responses id's.

So I have created a data flow. The conditional split is there, but I do not have a "Update Global Variable" Destination source.

Is there away to achieve this.

Basically this is the logic that I am trying to use

Dataflow --> Store Id's into Global Variable --> Data Flow update/insert Tables and Rows where Id in Gloabl Variable.

Is there another way this can be done?
Sorry I am very new to this, and would appreciate any help

Thanks

Andrew

View 2 Replies View Related

Integration Services :: How To Implement Data Driven Query Task In SSIS 2012

Jun 15, 2015

I have a requirement of migrating DTS package which is done in Sql Server 2000 to SSIS 2012.

I started with one package having data driven query task and done with source for which i chose OLE DB Source and given the required select query in ssis 2012

I'm stuck now and i'm unable to choose the relevant tools in ssis 2012 for binding, transformation,queries and lookup tabs used in dts 2000 for this DDQT.

View 4 Replies View Related

Transact SQL :: Iterate Through Table Rows And Do Conditional Update

Aug 11, 2015

I have a table with the following fields:

ID (int, identity)
Name (nvarchar(255))
Block (nvarchar(50))
Street (nvarchar(255))
Floor (nvarchar(50))
Unit (nvarchar(50))
Address1 (nvarchar(255))
Address2 (nvarchar(255))

I want to iterate through the table and populate Address1 as [Block] [Street] #[Floor]-[Unit].If the 'Floor' field contain a number < 10 (e.g., '8'), I want to add a '0' before it (e.g., '08'). Same for Unit.How would I do this using cursors (or other recommended method)?

View 4 Replies View Related

Transact SQL :: Conditional Update A Field From Multiple Tables

Sep 9, 2015

Conditional Update of a field from multiple tables..I have a target table with two fields: Date and ID..There three source tables: S1, S2, S3, each of them has three fields: Date, ID, and Score...Now I want to update the target table: put the ID into the ID field which has the highest Score from the three tables on each day.

View 13 Replies View Related

Trigger To Update One Record On Update Of All The Tables Of Database

Jan 3, 2005

hi!

I have a big problem. If anyone can help.

I want to retrieve the last update time of database. Whenever any update or delete or insert happend to my database i want to store and retrieve that time.

I know one way is that i have to make a table that will store the datetime field and system trigger / trigger that can update this field record whenever any update insert or deletion occur in database.

But i don't know exactly how to do the coding for this?

Is there any other way to do this?

can DBCC help to retrieve this info?

Please advise me how to do this.

Thanks in advance.

Vaibhav

View 10 Replies View Related

Transact SQL :: Firing After Update Trigger - On Table Row Update

Jul 8, 2015

I have a table where table row gets updated multiple times(each column will be filled) based on telephone call in data.
 
Initially, I have implemented after insert trigger on ROW level thinking that the whole row is inserted into table will all column values at a time. But the issue is all columns are values are not filled at once, but observed that while telephone call in data, there are multiple updates to the row (i.e multiple updates in the sense - column data in row is updated step by step),

I thought to implement after update trigger , but when it comes to the performance will be decreased for each and every hit while row update.

I need to implement after update trigger that should be fired on column level instead of Row level to improve the performance?

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

Trigger To Update A Table On Insert Or Update

Feb 15, 2008



Hello

I've to write an trigger for the following action

When a entry is done in the table Adoscat79 having in the index field Statut_tiers the valeur 1 and a date in data_cloture for a customer xyz

all the entries in the same table where the no_tiers is the same as the one entered (many entriers) should have those both field updated

statut_tiers to 1
and date_cloture to the same date as entered

the same action has to be done when an update is done and the valeur is set to 1 for the statut_tiers and a date entered in the field date_clture

thank you for your help
I've never done a trigger before

View 14 Replies View Related

Conditional Split For Insert Or Update Cause Dead Lock On Database Level

Aug 28, 2007

Hi

I am using conditional split Checking to see if a record exists and if so update else insert. But this cause database dead lock any one has suggestion?

Thanks

View 7 Replies View Related

Update Trigger To Update Another Table

Dec 17, 2001

I have an update trigger which fires from a transactiion table to update a parent record in another table. I am getting no errors, but also no update. Any help appreciated (see script below)

create trigger tr_cmsUpdt_meds on dbo.medisp for UPDATE as

if update(pstat)
begin
update med
set REC_FLAG = 2
from deleted dt
where med.uniq_id = dt.uniq_id
and dt.pstat = 2
and dt.spec_flag = 'kop'
end

View 1 Replies View Related

UPDATE Trigger Issue When Using UPDATE

May 30, 2008

I am trying to update a fields with an UPDATE statement but I keep getting the error message when I run the query.

Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.

I have this Update trigger that I know is causing the error message because I guess it's not built to manage multi-row updates.

Can someone help me re-write it. I also tried using the WHERE p.ID = p.ID but when I do that it modifies all rows in the modifieddate column instead of just the cells/rows that I'm updating

ALTER TRIGGER [dbo].[MultitrigCA]
ON [dbo].[ProdDesc]
AFTER UPDATE
AS

SET NOCOUNT ON

IF UPDATE (codeabbreviation)
UPDATE p
sET p.ModifiedDate = GETDATE()
FROM ProdDesc AS p
WHERE p.ID = (SELECT ID FROM inserted)

View 7 Replies View Related

INSTEAD OF UPDATE Trigger To Hold Update

Apr 3, 2008



hi!

i have a database with about 20 tables. i appended to each table a column "UpdatedOn", and i want to write a trigger to set the date of the update date in that column, using a trigger.

i want to avoid the trigger launching for the last column (UpdatedOn).

how can i detect the rows that changed, and modify only the update date/time?
i read something about TableName_Inserted and TableName_Deleted, but i would prefer to copy as generic as possible the data from there, meaning, not to write column names in my script.

another idea i thought about was to prevent the trigger executing if no other column except for UpdatedOn changed, but... i encounter some trouble, when i try to pass column name (as string) to UPDATE() function.(Error: Expecting ID or QUOTED_ID)

thank you in advance.

View 8 Replies View Related

Conditional Query

Mar 7, 2007

Hi again. Another problem though...
Can I make a query in if else statement? For example
int querynum;
if(querynum==1)<execute query1>
else if(querynum==2)<execute query2>
else <execute query3>

There is no problem with passing parameters(getquerynum) from my front end application to sql function. I can manage to do it. hehe.

the query looks like this:

DECLARE @querynum number
SET @querynum = @getquerynum

what i want to do is,

if(querynum==1) Select * from hremployees
else if(querynum==2) Select * from hrapplicants
else Select * from pspersonaldata

is it possible by having multiple queries in conditional statement?
if so, how to do it in sql language?
Thanks
-Ron-

View 14 Replies View Related

Conditional Query

Mar 15, 2007

I have a table having CusId, CusName, LocId and TvId among other fields.
I have 3 dropdown list which are are populated with cusid, locid and tovid.

I have added "Please Select" in all the 3 ddl with value -1.
Now i have written a sql statement as :

declare @CusId int
declare @LocId int
declare @TvId int

select CusId, CusName, LocId and TvId
From CustDetails
where CusId = @CusId
and LocId = @LocId
and TvId = @TvId


All i want is if any of the three variables has a value -1 then query should be modified. say @CusId has a value of -1 selected in dropdown list then query should become

select CusId, CusName, LocId and TvId
From CustDetails
where CusId IS NOT NULL
and LocId = @LocId
and TvId = @TvId


Please help me on this as i am totally new to sql.

Regards
Tingu

View 5 Replies View Related

Conditional Query

Apr 27, 2006

Hi,I'm trying to construct a query (in a stored procedure) which will have a number ofselection criteria based on input parameters. There are a number of these parameterswhose selection conditions they represent which all have to be true for a row to bereturned in the resultset.The basic query is:SELECT Store, StoreNumberFROM StoresWHERE ...I'm trying to come up with the WHERE clause.For example, I want to define a parameter named @ExcludeSpecialties which if it hasthe value 1, means to return all stores but exclude stores whose StoreNumber is inthe list (800, 802, 804). If the parameter has the value 0, then it means "don'tcare" and all StoreNumbers should be returned.One could certainly argue that there probably should have been an column in theStores row to indicate the store is a specialty store, rather than using a hard-wiredlist of numbers. But the current data schema cannot be easily changed. Besides, thelist never changes.Indeed, there is a Franchise bit column in the row which is selected by anotherparameter called @ExcludeFranchise whose WHERE predicate could be written as:WHERE Franchise = CASE WHEN @ExcludeFranchise = 1 THEN 0 ELSE Franchise ENDand if all the parameters were like this, I wouldn't be posting. Sadly, for theSpecialties test I'm stuck with a NOT IN list.This is easy enough to do in an IF/ELSE block, but there are several such similarparameters whose values may be specified in any combination. This, I think, makesIF/ELSE impractical as the number of IF/ELSE statements to handle all possiblecombinations would grow very quickly.I'm hoping there is a simple solution to this NOT IN list, and it's just that I can'tsee it.Can anyone help?Thanks,-- Jeff

View 2 Replies View Related

Conditional Query Results

Dec 19, 2006

Hello everybody,After several attempts of writing the query, I had to post myrequirement in the forum.Here is what I have, what I need and what I did.Table ACol1 Col21 Nm12 Nm23 Nm3Table BCol1 Col210 10020 200Table CCol1 (A.Col1) Col2 (B.Col1)1 102 10Table DCol1 (A.Col1) Col21 Value12 Value2I need results based on below criteria,1.Criteria - B.Col2 = 100ResultsetA.Col1 D.Col11 Value12 Value22.Criteria - B.Col2 =""A.Col1 D.Col11 Value12 Value23 NULL3.Criteria - B.Col2 =200Empty resultsetHere is the query I tried, but looks its not working. Probably there isa better way to do this.DDL and DML statements:create table #tab1 (a1 int, a2 nvarchar(20))create table #tab2 (b1 int, b2 int)create table #tab3 (c1 int, c2 int)create table #tab4 (d1 int, d2 nvarchar(20))insert into #tab1 values (1, 'nm1')insert into #tab1 values (2, 'nm2')insert into #tab1 values (3, 'nm3')insert into #tab2 values (10, 100)insert into #tab2 values (20, 200)insert into #tab3 values (1, 10)insert into #tab3 values (2, 10)insert into #tab4 values (1, 'value1')insert into #tab4 values (2, 'value2')selecta.a1, d.d2from #tab1 aleft join #tab3 bon a.a1 = b.c1left join #tab2 con b.c2 = c.b1left join #tab4 don a.a1 = d.d1wherec.b2 = [100 or 200 or ''] or exists (select 1 from #tab4 dwhere a.a1 = d.d1and c.b2 = [100 or 200 or ''] )The above query works well to give results for Criteria 1 and Criteria3, but doesn't return for '' (criteria 2). I couldn't manage crackingthe solution. I shall try once again, but meanwhile if anyone couldhelp me in this, that would be great.Thanks.

View 3 Replies View Related







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