下面是一個替代的解決方案。
它不是「動態SQL」,但它是靈活的,「乾淨」的恕我直言。
Use Northwind
GO
declare @holder table (ProductName nvarchar(40))
Insert into @holder (ProductName)
select
'Chai' union all select 'Chang' union all select 'Aniseed Syrup'
SELECT
[ProductID]
,[ProductName]
,[SupplierID]
,[CategoryID]
,[QuantityPerUnit]
,[UnitPrice]
,[UnitsInStock]
,[UnitsOnOrder]
,[ReorderLevel]
,[Discontinued]
FROM
[dbo].[Products] prod
where
exists (select null from @holder innerH where innerH.ProductName = prod.ProductName)
declare @holderCOUNT int
select @holderCOUNT = count(*) from @holder
SELECT
[ProductID]
,[ProductName]
,[SupplierID]
,[CategoryID]
,[QuantityPerUnit]
,[UnitPrice]
,[UnitsInStock]
,[UnitsOnOrder]
,[ReorderLevel]
,[Discontinued]
FROM
[dbo].[Products] prod
where
(@holderCOUNT = 0 OR (exists (select null from @holder innerH where innerH.ProductName = prod.ProductName) ))
delete from @holder
select @holderCOUNT = count(*) from @holder
SELECT
[ProductID]
,[ProductName]
,[SupplierID]
,[CategoryID]
,[QuantityPerUnit]
,[UnitPrice]
,[UnitsInStock]
,[UnitsOnOrder]
,[ReorderLevel]
,[Discontinued]
FROM
[dbo].[Products] prod
where
(@holderCOUNT = 0 OR (exists (select null from @holder innerH where innerH.ProductName = `enter code here`prod.ProductName) ))
那麼是什麼問題? –
嘗試轉義值的單引號。 – user2989408
什麼是語法錯誤?運行'SELECT @ SQL'來查找你的查詢是什麼,然後運行這個獨立的,會發生什麼? – Tom