INSERT INTO dbo.VehiclesCategories ( VehicleId, CategoryId )
VALUES ( t1.ID , t2.ID)
SELECT t1.ID, t2.ID
FROM dbo.Vehicle t1
inner JOIN dbo.VehicleCategory t2 ON t1.Category = t2.Name
在上面的SQL中,我想在M:M连接表中插入两个值。 SELECT语句工作正常,我得到了所需的结果。 INSERT语句抛出以下错误:
Msg 128, Level 15, State 1, Line 2
The name "t1.ID" is not permitted in this context. Valid expressions are constants, constant expressions, and (in some contexts) variables. Column names are not permitted.
如何将两个值(t1.ID和t2.ID)插入表中?
答案 0 :(得分:7)
那是因为在INSERT的上下文中,t1
和t2
不存在。
如果你将这两个查询结合起来,我认为它会完全符合你的要求:
INSERT INTO dbo.VehiclesCategories ( VehicleId, CategoryId )
SELECT t1.ID, t2.ID
FROM dbo.Vehicle t1
inner JOIN dbo.VehicleCategory t2 ON t1.Category = t2.Name
答案 1 :(得分:0)
根本不要包含VALUES (t1.ID, t2.ID)
部分。
答案 2 :(得分:0)
试试这个
INSERT dbo.VehiclesCategories ( VehicleId, CategoryId )
SELECT t1.ID, t2.ID
FROM dbo.Vehicle t1
JOIN dbo.VehicleCategory t2 ON t1.Category = t2.Name
答案 3 :(得分:0)
只需从VALUES ( t1.ID , t2.ID)
insert into
即可