用来自不同表中不同列的数据替换空列

时间:2015-11-24 16:31:30

标签: sql-server sql-server-2012 sql-insert

我有两张桌子

100 HL Road Frame   HL Road Frame - Black, 58   FR-R92B-58  Black   1431.50 1059.31 Road Frames 183 NULL
101 HL Road Frame   HL Road Frame - Red, 58 FR-R92R-58  Red 1431.50 1059.31 Road Frames 183 NULL
102 Sport-100   Sport-100 Helmet, Red   HL-U509-R   Red 34.99   13.09   Helmets 112 NULL
103 Sport-100   Sport-100 Helmet, Black HL-U509 Black   34.99   13.09   Helmets 112 NULL
104 Mountain Bike Socks Mountain Bike Socks, M  SO-B909-M   White   9.50    3.40    Socks   132 NULL

和类别:

╔═══════╦═══════════════════╗
║     1 ║ Bib-Shorts        ║
║     2 ║ Bike Racks        ║
║     3 ║ Bike Stands       ║
║     4 ║ Bottles and Cages ║
║     5 ║ Bottom Brackets   ║
╚═══════╩═══════════════════╝

我正在尝试替换第一个表中的空值,并使用第二个表中的类别ID填充它们,我认为插入语句将无法正常运行我认为不会像我想的那样。

CREATE TABLE PRODUCTCATEGORY
(
    categoryID       INT IDENTITY(1, 1) CONSTRAINT pk_PRODUCTCATEGORY_category_ID 
    PRIMARY KEY,
    categoryname     VARCHAR(50)
) 

是表格

ALTER TABLE product
    ADD categoryID INT
INSERT INTO product
SELECT categoryID
FROM   PRODUCTCATEGORY

我得到的错误是Msg 213,Level 16,State 1,Line 18 列名或提供的值数与表定义不匹配。进行插入

赞赏任何意见。

2 个答案:

答案 0 :(得分:0)

你所说的基本上是:

CREATE UNIQUE INDEX unq_pages_staff_3 ON pages_staff(pages_admin_page, pages_admin_type, pages_admin_user);

SQL告诉你的是INSERT INTO product(id, short_name, long_name, model number, color, price, smaller_price, type_name, type_id, what_does_this_value_even_represent) VALUES (1,'Bib-Shorts'), (2,'Bike Racks'), (3,'Bike Stands'), (4,'Bottles and Cages'), (5,'Bottom Brackets');

答案 1 :(得分:0)

更改表后,您应该执行UPDATE

 UPDATE product P
 SET P.categoryID = PC.categoryID 
 FROM PRODUCTCATEGORY PC
 WHERE P.ID = PC.ID
   AND P.categoryID  IS NULL