IF NOT EXISTS (SELECT TOP 1 CityName FROM dbo.City WHERE [Name] = 'Default City')
BEGIN
INSERT dbo.City ( CityName, Status,CityCategoryId) VALUES
(N'Default City', 0, (SELECT CityCategoryId FROM dbo.CityCategory WHERE [CityCategoryName] = N'Default City Category'))
END
GO
我有上面的查询在SQL Server 2012中正常运行但在SQL Server 2005中失败,并显示以下错误消息。
在此上下文中不允许使用子查询。只允许使用标量表达式。
答案 0 :(得分:1)
像这样更改insert
。
INSERT dbo.City
(CityName,Status,CityCategoryId)
SELECT N'Default City',0,CityCategoryId
FROM dbo.CityCategory
WHERE [CityCategoryName] = N'Default City Category'
答案 1 :(得分:1)
尝试使用变量@CityCategoryId.
我不知道@CityCategoryId的类型。您可以使用所需的数据类型。
IF NOT EXISTS (SELECT TOP 1 CityName FROM dbo.City WHERE [Name] = 'Default City')
BEGIN
Declare @CityCategoryId AS NVARCHAR(100)
SELECT @CityCategoryId = CityCategoryId FROM dbo.CityCategory
WHERE [CityCategoryName] = N'Default City Category'
INSERT dbo.City( CityName, Status, CityCategoryId)
VALUES
(N'Default City', 0, @CityCategoryId)
END
GO
答案 2 :(得分:0)
试试这样。我不确定......
IF NOT EXISTS (SELECT TOP 1 CityName FROM dbo.City WHERE [Name] = 'Default City')
BEGIN
INSERT dbo.City ( CityName, Status,CityCategoryId)
SELECT 'Default City',0, CityCategoryId FROM dbo.CityCategory WHERE [CityCategoryName] = N'Default City Category'
END
GO