-1

有人可以解释为什么下面给我“必须声明标量变量@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
4

2 回答 2

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
于 2013-10-09T13:43:12.157 回答
1

当您在 dynamicSQl 语句中连接事物时,构建语句的所有部分必须是 varchar 或 nvarchar。这是 SQL 的限制。

另一方面,您不需要动态 sql,因为您已经创建了一个表。

SELECT * FROM TestTable t
LEFT join @facilities f on f.n = t.facilityNO
于 2013-10-09T13:38:41.463 回答