简体   繁体   中英

How to alter a table

How do I alter a table with an existing column from another table using a left join?

This is my code for a left join. It works as a select.

USE [Metamodel]
GO 

      SELECT a.*,
      b.[TABLE_SIZE]   
      FROM guest.MMT_T a
      left join [guest].[SYSTEM_INFO]  b on a.TABLE_NAME = b.TABLE_NAME

GO

What you could do is add a new blank/null column and then set it to the desired result by a mix of update table and a join.

I could look something like this

CREATE TABLE firstTable 
(
firstColumn NVARCHAR(2)
, correspondingText NVARCHAR(20)
)

CREATE TABLE secondTable 
(
secondColumn NVARCHAR(2)
, correspondingText NVARCHAR(20)
)

-- Insert some values to join with later
INSERT INTO firstTable (firstColumn, correspondingText)
VALUES
('1', 'firstText')
-- Insert some values to join with later    
INSERT INTO secondTable (secondColumn,correspondingText)
VALUES
('1', 'secondText')

-- Add a new column to the first table 
ALTER TABLE firstTable
ADD columnFromOtherTable NVARCHAR(20) 

-- I update the first table, with the added column, by setting t1.firstColumn(first 
-- table and first column) = t2(Second table and second column) equal eachother
second tables 
UPDATE t1
SET t1.columnFromOtherTable = t2.correspondingText
FROM firstTable t1
LEFT JOIN secondTable t2 ON t1.firstColumn = t2.secondColumn

SELECT firstColumn, correspondingText, columnFromOtherTable FROM firstTable

This was done in Microsoft SQL Server Management Studio 2017. The code is fast written and is most likely not best practice.

See if you can apply it to your example. Otherwise, ask again :)

Regards, Daniel

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