简体   繁体   中英

SQL Server Insert rows from a table into another table with null value

Ok so I have just created a table _amazonProduct with some columns:

ID
ProductID
ProductPrice

Now I have a product table with many columns, more than 50.

The column I want to insert is Id from product table into ProductID in _amazonProduct . All other values will be set to null.

Some things I have tried.

UPDATE [Azure_Test].[dbo].[_amazonProduct]
SET [Azure_Test].[dbo].[_amazonProduct].[ProductID] = [Azure_Test].[dbo].[Product].[Id]
FROM [Azure_Test].[dbo].[_amazonProduct]
JOIN [Azure_Test].[dbo].[Product] ON [Azure_Test].[dbo].[_amazonProduct].[ProductID] = [Azure_Test].[dbo].[Product].[Id]

Also tried:

SELECT [Azure_Test].[dbo].[Product].[Id]
INTO [Azure_Test].[dbo].[_amazonProduct].[ProductID]
FROM [Azure_Test].[dbo].[Product]

Also tried:

UPDATE [Azure_Test].[dbo].[_amazonProduct]
SET [ProductID] = (
    SELECT [Id]
    FROM [Azure_Test].[dbo].[Product]
)

Anyone able to help me out, not sure exactly how to go about this.

Cheers

try: --Copy strtuct:

SELECT *
INTO [Azure_Test].[dbo].[_amazonProduct]
FROM [Azure_Test].[dbo].[Product] WHERE 1=0
GO
sp_rename '_amazonProduct.ID','ProductID','COLUMN'
GO

--Insert into new table:

insert into [Azure_Test].[dbo].[_amazonProduct](ProductID)
 select ID FROM [Azure_Test].[dbo].[Product]

Also you ca use dynamic script。

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