Tag Archives: update

UPDATE Statement with Aggregate function in WHERE condition

I seen many places developer get confused about how to use AGGREGATE function in WHERE condition with UPDATE statement. Suppose I have one table with user name and percentage. I want to update percentage if one user’s percentage sum is greater or lower than some value.

–table used

create table test11

(

uName varchar(20),

percentage int

)

–data used

INSERT INTO test11

SELECT ‘RITESH’,90 UNION ALL

SELECT ‘RAJAN’,75 UNION ALL

SELECT ‘RITESH’,80 UNION ALL

SELECT ‘ALKA’,70

–update query

update test11 set percentage=100

where uname=‘Ritesh’

AND

percentage in

(

select percentage from test11

WHERE uname=‘Ritesh’ group by percentage having sum(percentage)>70

)

Reference: Ritesh Shah

http://www.sqlhub.com
Note: Microsoft Books online is a default reference of all articles but examples and explanations prepared by Ritesh Shah, founder of
http://www.SQLHub.com

Microsoft SQL Server Blog. Fight the fear of SQL with SQLHub.com. Founder is Ritesh Shah

UPDATE() function with Trigger in SQL Server 2005:

UPDATE() function in Trigger will is one of the very useful function related to trigger. UPDATE() function will help you to know that which column is going to update. Let us see how will it work?

–create table1 for demo

CREATE TABLE CustInfo

(

CustId INT Identity(1,1),

Name VARCHAR(10),

Country Varchar(10),

)

GO

–insert records in above table

INSERT INTO CustInfo

SELECT ‘RITSEH’,’India’ UNION ALL

SELECT ‘RAJAN’ ,’Hindustan’

GO

–CREATE trigger to check which field

–we are updating

CREATE TRIGGER UpdateCheck ON CustInfo

AFTER UPDATE

AS

IF UPDATE(Name)

BEGIN

PRINT ‘YOU HAVE UPDATED NAME FIELD’

END

ELSE

BEGIN

PRINT ‘YOU HAVE NOT UPDATED NAME FIELD’

END

–check this out

UPDATE CustInfo SET Name =‘R.Shah’ WHERE Name=‘RAJAN’

As we are updating Name field, we will see first message as condition will fall in IF part.

Reference: Ritesh Shah
http://www.sqlhub.com
Note: Microsoft Books online is a default reference of all articles but examples and explanations prepared by Ritesh Shah, founder of
http://www.SQLHub.com

Microsoft SQL Server Blog. Fight the fear of SQL with SQLHub.com. Founder is Ritesh Shah