简体   繁体   中英

Insert values for whole column in SQL Server

Is there any way to insert different values for specific column, not whole row in SQL Server. Classic UPDATE SET would set all to same value.

在此处输入图片说明

For example I want to set some int values to Ranking column for each of 3 rows, without dropping them and doing complete new insert into.

Use row_number()

  update a set ranking =rn from tablename a join 
    (select id,name, row_number() over(order by id) as rn
        from tablename) b on a.id=b.id

do update

update tabale 
  set ranking= your_va

   with cte as
   (
    select * ,row_number() over(order by id) rn
   ) update cte set ranking=rn where id<=3

What value do you want to set ranking to?

Just any value:

update mytable set ranking = id;

Certain values:

update mytable set ranking =
  case name 
    when 'Positive' then 1
    when 'Neutral'  then 2
    when 'Negative' then 3
                    else 4
  end;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM