我正在尝试从使用变量生成的字符串中执行 SQL 查询。此 SP 生成一个 Select 查询,当我手动执行此查询时它可以工作,但是当它在 SP 中时,会出现类似的错误
消息 911,级别 16,状态 4,过程 sp_Products_Select,第 26 行
数据库“SELECT *,(从 SectionID = Products 的部分中选择部分”不存在。确保输入的名称正确。
从 SP 生成的查询
SELECT
*,
(Select Section
From Sections
Where SectionID = dbo.Products.SectionID) as Section,
(Select Category
From Categories
Where CategoryID = Products.CategoryID) as Category
FROM
Products
WHERE
1 = 1AND (Status = 1 OR Status = 0)
我的SP是,
ALTER PROC [dbo].[sp_Products_Select]
@ProductID int,
@Status int,
@CategoryID int,
@SectionID int
AS
DECLARE @SQL varchar(500)
SET @SQL ='SELECT *,(Select Section From Sections Where SectionID = Products.SectionID) as Section,(Select Category From Categories Where CategoryID = Products.CategoryID) as Category FROM Products WHERE 1 = 1';
IF @ProductID <> '0' BEGIN
SET @SQL += 'AND ProductID = @ProductID';
END
IF @Status <> 0 BEGIN
SET @SQL += 'AND Status = @Status';
END ELSE BEGIN
SET @SQL += 'AND (Status = 1 OR Status = 0)';
END
IF @CategoryID <> '0' BEGIN
SET @SQL += 'AND CategoryID = @CategoryID';
END
IF @SectionID <> '0' BEGIN
SET @SQL += 'AND SectionID = @SectionID';
END
EXEC @SQL
如何从 SP 正确执行此查询?