参考我的question我正在尝试这个选择语句并收到错误
Select * From
(SELECT * FROM FruitCrate WHERE FruitName IN (' +@FruitNames+ '))
WHERE FruitCrate.Eatable= 1
错误
关键字'WHERE'附近的语法不正确。
修改
USE [DataBaseName]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[SPName]
(
@FruitNames
)
AS
exec('SELECT *
FROM FruitCrate
WHERE FruitName IN (' +@FruitNames+ ')
and Eatable = 1')
答案 0 :(得分:2)
您应该将子查询命名为
Select * From
(SELECT * FROM FruitCrate WHERE FruitName IN (' +@FruitNames+ ')) tab
WHERE tab.Eatable= 1
您应该将代码用作动态sql
exec('Select * From
(SELECT * FROM FruitCrate WHERE FruitName IN (' +@FruitNames+ ')) tab
WHERE tab.Eatable= 1')
它适用于'apple','strawberry','banana'
Select * From
(SELECT * FROM FruitCrate WHERE FruitName IN ('apple','strawberry','banana')) tab
WHERE tab.Eatable= 1
答案 1 :(得分:2)
您无法将逗号分隔的字符串传递给in
运算符。如果您使用and
条件,则只需要1个查询。
exec('SELECT *
FROM FruitCrate
WHERE FruitName IN (' +@FruitNames+ ')
and FruitCrate.Eatable= 1'
如果您想执行动态查询(这里就是这种情况),您必须使用exec
答案 2 :(得分:1)
试试这个:
Select * From
(SELECT * FROM FruitCrate WHERE FruitName IN (' +@FruitNames+ ')) as FruitCrateRes
WHERE FruitCrateRes.Eatable= 1
您使用了表名FruitCrate而没有重命名from子句的子查询输入
答案 3 :(得分:0)
你为什么不使用
SELECT * FROM FruitCrate WHERE FruitName IN (' +@FruitNames+ ')
WHERE FruitCrate.Eatable= 1
可能使用子查询,SQL引擎无法识别最后FruitCrate
中的WHERE
,因为未指定子查询名称。
您的IN
条款也可能被滥用!