有人可以解释为什么下面给我“必须声明标量变量@facilities”。但如果我使用VARCHAR而不是我创建的类型,可以正常工作吗?我该如何解决这个问题?
TIA
--CREATE TYPE integer_list AS TABLE (n int NOT NULL PRIMARY KEY)
--DROP PROCEDURE spTestTVP
CREATE PROCEDURE spTestTVP (
@facilities integer_list READONLY
--@facilities varchar(100)
)
AS
DECLARE @sql nvarchar(4000)
SET @sql = 'SELECT * FROM TestTable'
SET @sql = @sql + ' WHERE 1=1 '
IF @facilities IS NOT NULL
SET @sql = @sql + ' AND (FacilityNo IN (' + @facilities + ') OR FacilityNo IS NULL)'
EXEC sp_executesql @sql
答案 0 :(得分:1)
当您在dynamicSQl语句中连接事物时,构建语句的所有部分必须是varchar或nvarchar。这是SQL的限制。
另一方面,由于您创建了一个表,因此不需要动态sql。
SELECT * FROM TestTable t
LEFT join @facilities f on f.n = t.facilityNO
答案 1 :(得分:1)
DECLARE @items VARCHAR(MAX)
SELECT@items = COALESCE(@items+',' ,'') + n
FROM @facilities
DECLARE @sql nvarchar(4000)
SET @sql = 'SELECT * FROM TestTable'
SET @sql = @sql + ' WHERE 1=1 '
IF @facilities IS NOT NULL
SET @sql = @sql + ' AND (FacilityNo IN (' + @items + ') OR FacilityNo IS NULL)'
EXEC sp_executesql @sql
或不动态如下:
SELECT t.* FROM TestTable as t
left outer join
@facilities as f
on
f.n = t.FacilityNo
where
t.FacilityNo is null
or
f.n is not null