Update rows based on another single row selected without DECLAREing variables
How to update rows based upon another single row.
I want to update these:
SELECT field_one, field_two, field_three
FROM some_table WHERE user_ID = 296
With the values in this SELECT:
SELECT TOP 1 * field_one, field_two, field_three
FROM some_table
WHERE user_ID = 500
ORDER BY ID
Currently I am only updating field_one using:
DECLARE @field_one nvarchar(1000)
SELECT @field_one = field_one
FROM some_table WHERE user_ID = @copy_user_ID
UPDATE some_table
set field_开发者_Python百科one = @field_one
where user_ID = @user_ID
Is there a way to do this with every field without having to DECLARE all of the variables?
Let's see, in FoxPro you could use SCATTER and GATHER :-)
But here, you can do this:
UPDATE Table1
SET Field_one = a.Field_one,
Field_two = a.Field_two,
Field_three = a.Field_three
FROM
(SELECT TOP 1 field_one, field_two, field_three
FROM some_table WHERE user_ID = 500
ORDER BY ID) a
WHERE user_ID = 296
For an extra tip. You can get a list of all the fields of a table, comma separated, in SSMS by opening up the Object Explorer pane showing the table, then click on the plus(+) sign to show the folders under the table. Then just click on the Columns folder and drag it to your query pane.
精彩评论