Click here to Skip to main content
15,887,596 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi

I want to update one of the columns of my table.

I have to use subquery to reach to the desired record, but it seems that we aren't allowed to use subquery in front of UPDATE.

what is the best way to update the column with subquery ?



SQL
UPDATE 	(SELECT TOP(1)* FROM (SELECT * FROM TempTable WHERE Column1='1' AND Column2='2') AS AAA )AS BBB
	
		SET Column3='1'
Posted

SQL
UPDATE 	TempTable
	WHERE	ColumnID = (Select	Top 1   ColumnID
				From	TempTable
				Where	Column1='1' AND Column2='2')
	SET Column3 = '1'
 
Share this answer
 
Hi
If your table has a unique identity columns as ID, you can use from bellow query:

SQL
Declare	@RowID	As	BigInt
Set	@RowID	=	Select	Top 1   ColumnID
				From	TempTable
				Where	Column1='1' AND Column2='2'
UPDATE 	TempTable
	WHERE	ColumnID = @RowID
	SET Column3 = '1'


I hope it's helpful for you.
 
Share this answer
 
Comments
Behno0o0oD 14-Jul-13 2:56am    
TnX

It seems that I have to add ID Column;)
Reza Alipour Fard 14-Jul-13 3:36am    
I have a suggestion for you: Add unique identify column as ID to all tables. This help you to easily write query for your purpose. If my answer it's OK for you please give rate 5 (out of 5) to my answer. Best regards
Behno0o0oD 14-Jul-13 3:36am    
It seems that SQLServer CE does not support variables. What is the next solution?
TnX
Reza Alipour Fard 14-Jul-13 3:54am    
See solution 2.
_Asif_ 14-Jul-13 5:40am    
instead of adding more solutions you should improve your first solution.
Hi
If your table has a unique identity columns as ID, you can use from bellow query:

SQL
UPDATE 	TempTable
	WHERE	ColumnID = (Select	Top 1   ColumnID
				From	TempTable
				Where	Column1='1' AND Column2='2')
	SET Column3 = '1'



Please use from this query.
 
Share this answer
 
v2
Comments
Behno0o0oD 14-Jul-13 4:16am    
I tried this but it seems that there is a problem with "TOP 1 ColumnID".

Maybe because of SQLServer CE!
Reza Alipour Fard 14-Jul-13 4:36am    
You must use '(' before select and ')' in enf of select.
Please attention bellow query:
UPDATE TempTable
WHERE ColumnID = (Select Top 1 ColumnID
From TempTable
Where Column1='1' AND Column2='2')
SET Column3 = '1'

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900