Sunday, July 20, 2014

UPDATE Command in SQL SERVER 2012

UPDATE:

It is used to modify the contents in the table,It is used to work with rows or records in the table.

We can update single column data or multiple columns data.Specific data  can be updated based on some condition,this condition is specified using where clause.

Syntax:

UPDATE <TABLE_NAME>
SET <COLUMN_NAME>=<EXPR/VALUE>
[WHERE CLAUSE]

SELECT * FROM EMP20

UPDATE EMP20
SET JOB='ANALYST' --will update the column job with 'ANALYST

SELECT * FROM EMP20

UPDATE EMP20
SET JOB='MANAGER'
WHERE ENO=1004 --Will update the job of employee whose number is 1004 with 'MANAGER'

SELECT * FROM EMP20

UPDATE EMP20
SET JOB='SALESMANAGER'
WHERE ENAME='VINAY' --Will update the job of employee whose name is 'VINAY' with 'MANAGER'

UPDATE EMP20
SET JOB='PROGRAMMERS'
WHERE JOB='ANALYST'--Will update the job of employee whose job is 'ANALYST' with
'PROGRAMMERS'

SELECT * FROM EMP20

Example2
CREATE TABLE STUDENT
(
SNO INT,
SNAME VARCHAR(15),
MAT INT,
PHYS INT,
CHEM INT,
TOTAL INT,
AVEG DECIMAL(4,2)
)
SELECT * FROM STUDENT

INSERT INTO STUDENT(SNO,SNAME,MAT,PHYS,CHEM) VALUES(101,'VINAY',50,70,80)
INSERT INTO STUDENT(SNO,SNAME,MAT,PHYS,CHEM) VALUES(102,'ANIL',60,90,72)
INSERT INTO STUDENT(SNO,SNAME,MAT,PHYS,CHEM) VALUES(103,'PAVAN',58,71,86)
INSERT INTO STUDENT(SNO,SNAME,MAT,PHYS,CHEM) VALUES(104,'SURESH',90,82,66)
INSERT INTO STUDENT(SNO,SNAME,MAT,PHYS,CHEM) VALUES(105,'RAMESH',85,77,73)

UPDATE STUDENT
SET TOTAL=MAT+PHYS+CHEM,
AVEG=(MAT+PHYS+CHEM)/3--'Here we are going to update the AVEG column by evaluating the expression with the help of MAT/PHY and CHEM columns.

UPDATE STUDENT
SET MAT=70
WHERE SNAME='VINAY'--'we are updating the maths marks of a student whose name is 'VINAY'
UPDATE STUDENT
SET SNAME='RAJESH'
WHERE SNO=105--'we are updating the name of a student whose student id 105

SELECT * FROM STUDENT

 **If we don't use where clause in UPDATE Command the update will reflect to all the table based on set clause.

Thanks
GSV

No comments: