我有一个插入语句,我想要进行2次插入。我有以下代码:
INSERT INTO [dbo].[Licemb]
([Lic_Id],
[LicEmb_EmbTS],
[LicEmb_EmbOffset])
SELECT TOP 1
Lic_ID,
'00:00:00',
-7
FROM dbo.Lics
WHERE Org_ID = 2
ORDER BY NP_ID DESC
UNION ALL
SELECT TOP 1
Lic_ID,
'00:00:00',
-7
FROM dbo.Lics
WHERE Org_ID = 4
ORDER BY NP_ID DESC
然而,我一直收到语法错误,在搜索一段时间后我无法找到解决方法。
错误:
Incorrect syntax near the keyword 'UNION'.
如何修改此代码,以便我可以使用单个语句进行2次选择插入?
非常感谢任何帮助。
答案 0 :(得分:3)
您的整个工会声明只能有一个订单。
如果你需要订购每个选择,你需要运行一个子查询并将它们联合起来
所以
INSERT INTO [dbo].[Licemb]
([Lic_Id],
[LicEmb_EmbTS],
[LicEmb_EmbOffset])
select id,daytime,embargo from (
SELECT TOP 1
Lic_ID AS id,
'00:00:00' AS daytime,
-7 AS embargo
FROM [NLASQL].dbo.Lics
WHERE Org_ID = 2
ORDER BY NP_ID DESC)
UNION ALL
select id,daytime,embargo from (
SELECT TOP 1
Lic_ID AS id,
'00:00:00' AS daytime,
-7 AS embargo
FROM [NLASQL].dbo.Lics
WHERE Org_ID = 4
ORDER BY NP_ID DESC)
这不是一个理想的解决方案,并会问为什么需要订购每组数据,然后从这个角度处理问题。
答案 1 :(得分:1)
如果您使用union (all)
,则只能有一个order by
,即在最后一个联合查询之后。此order by
适用于union
。