Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
279 views
in Technique[技术] by (71.8m points)

sql server - Populate column based on another column in SQL

What's the best way to populate column A with name in df1 based on the common column ID of df1 and df2?

df1

   ID   A 
   122  nan
   233  nan
       ...

df2

   ID   B    name 
   122  10   real_name1
   233  20   real_name2
       ... 

to get:

   ID   A 
   122  real_name1
   233  real_name2
        ...

Edit: I would also like to change the column name A to new_column_name so the expected output looks like this:

   ID   new_column_name
   122  real_name1
   233  real_name2
        ...

Update:

Tried:

UPDATE t1
SET A = t2.name
FROM df1 t1
INNER JOIN df2 t2
    ON t2.ID = t1.ID;

and it caught error:

Msg 8152, Level 16, State 2, Line 48
String or binary data would be truncated.
The statement has been terminated.

Update2:

Table definitions

df1:

CREATE TABLE [dbo].[df1](
    [ID] [nvarchar](20) NULL,
    [SUB_ID2] [nvarchar](15) NOT NULL,
    [DATE] [datetime2](7) NULL,
    [MONTH] [nvarchar](4000) NULL,
    [QTY] [numeric](20, 8) NOT NULL,
    [SUB_ID] [nvarchar](15) NOT NULL,
    [X] [nvarchar](20) NULL,
    [SUBURB_ID] [nvarchar](30) NULL,
    [PROJECT_NAME] [nvarchar](160) NULL,
    [A] [varchar](10) NOT NULL
) ON [PRIMARY]

df2:

CREATE TABLE [dbo].[df2](
    [ID] [nvarchar](46) NULL,
    [NAME1] [nvarchar](50) NULL,
    [IDx] [nvarchar](15) NULL,
    [P] [nvarchar](50) NULL,
    [Q] [nvarchar](50) NULL,
    [Z] [nvarchar](50) NULL,
    [Y] [nvarchar](30) NULL,
    [MARK] [nvarchar](10) NULL,

) ON [PRIMARY]
question from:https://stackoverflow.com/questions/65930360/populate-column-based-on-another-column-in-sql

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If you actually want to update the first table, then use:

UPDATE t1
SET A = t2.name
FROM df1 t1
INNER JOIN df2 t2
    ON t2.ID = t1.ID;

If you really wanted to express the update logic using a join, you could use an updatable CTE:

WITH cte AS (
    SELECT t1.A, t2.name
    FROM df1 t1
    INNER JOIN df2 t2 ON t2.ID = t1.ID
)

UPDATE cte
SET A = name;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...