gpt4 book ai didi

SQL 错误 : "Must declare the scalar variable" when passing a table parameter to a table-valued function

转载 作者:行者123 更新时间:2023-12-05 01:13:35 25 4
gpt4 key购买 nike

以下简单的 SQL 示例返回错误。

这是传递给表值函数的表类型:

CREATE TYPE Ids
AS TABLE
(
Id int NOT NULL,
PRIMARY KEY( Id )
);
GO

下面是失败的表值函数:

CREATE FUNCTION GetIds
(
@ids -- or null
Ids READONLY
)
RETURNS
@result
TABLE
(
EachId int
)
AS
BEGIN
IF @ids IS NOT NULL
INSERT INTO @result
SELECT Id
FROM @ids;
RETURN;
END;
GO

返回的错误是:

Msg 137, Level 16, State 1, Procedure GetIds, Line 28
Must declare the scalar variable "@ids".

我读过一些帖子说当 SQL 兼容性级别太旧时会发生这种情况,但以下返回 100:

SELECT compatibility_level 
FROM sys.databases
WHERE name = 'TheDatabaseName';

如有任何建议,我们将不胜感激。

最佳答案

我告诉你表型参数就像一个数据表。

所以,如果你想在上面加上 if 条件,

只需更改您的 if 函数条件,如下所示:

IF (select count(*) from @ids) > 0

完整的功能代码为:

CREATE FUNCTION GetIds
(
@ids Ids READONLY
)
RETURNS @result TABLE(EachId int)
AS
BEGIN
IF (select count(*) from @ids) > 0
INSERT INTO @result
SELECT Id FROM @ids;
RETURN;
END;

关于SQL 错误 : "Must declare the scalar variable" when passing a table parameter to a table-valued function,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30339535/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com