How to change column name and change value in table using stored procedure?

I have a table below:

Desk_name | head ali | john cars ln | max pol fr | max jus | john 

I want to create a stored procedure to have in return:

 Name | sector_head ali mm | john cars ln | max pol fr | max jus mm | john 

As you can see, the column name has changed (from "Name" to "Desk_name"), and each name in the "Name" column has the abbreviation "mm" at the end of each value, if it is one word (ali and jus).

How can I make such a stored procedure (I use sql server)?

thanks

+4
source share
4 answers

You need to specify ALIAS , for example

 SELECT CASE WHEN LTRIM(RTRIM(Desk_name)) LIKE '% %' -- finds any space in string THEN Desk_name ELSE Desk_name + ' mm' END AS Name, head AS sector_head FROM tableName 

SQLFiddle Demo

+4
source

try the following:

In sql server

 select case when charindex(' ',ltrim(rtrim(Desk_name)))=0 then Desk_name+' mm' else Desk_name end as Name , head as sector_head from your_table 


SQL script demo

+4
source
 SELECT CASE WHEN Desk_name = 'ali' OR Desk_name = 'jus' THEN Desk_name + ' mm' ELSE Desk_name END AS Name, head AS sector_head FROM DeskName 
0
source

As I understand it, before updating the table, you need to rename the Desk_name column. To do this, you can try the following:

 sp_RENAME 'YourTableName.Desk_name' , 'Name', 'COLUMN' 

It should rename your column. After that, you should use Joe or John to update the records in the table.

0
source

Source: https://habr.com/ru/post/1437529/


All Articles