Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update the same table in SQL Server

Tags:

sql

sql-server

I was trying to update the same table data from same table data.

My SP is as shown below :

UPDATE T1
SET T1.Name = T2.Name
   , T1.Age = T2.Age
   , T1.Subject = T2.Subject
FROM Student T1
   , Student T2
WHERE T1.StudentID = @OldID
   AND T2.StudentID = @NewID

When I am executing this query, there is no error. But the update is not working.

[here NO Common column values to compare like T1.StudentID = T2.StudentID]

like image 759
Sunil Shah Avatar asked Oct 11 '12 14:10

Sunil Shah


2 Answers

Try this:

UPDATE t1
SET t1.name = t2.name, t1.age = t2.age, t1.subject = t2.subject
FROM student t1
INNER JOIN
student t2
ON t1.StudentID = @oldID
AND t2.StudentID = @NewID

The full example is here

like image 144
Gidil Avatar answered Oct 15 '22 22:10

Gidil


Try this one , you are using wrong alias .

UPDATE T1 SET Name = T2.Name
, Age = T2.Age
, Subject = T2.Subject
 FROM Student T1
, Student T2
WHERE T1.StudentID = @OldID
AND T2.StudentID = @NewID
like image 20
Hiren Dhaduk Avatar answered Oct 16 '22 00:10

Hiren Dhaduk