SQL 存储过程返回一个字符串?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13649284/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-01 12:23:31  来源:igfitidea点击:

Stored Procedure returning a string?

sqlsql-server-2008stored-proceduresreturnvarchar

提问by Pascal Weber

Possible Duplicate:
Conversion failed when converting the nvarchar value ‘Internet Explorer 3 original' to data type int

可能的重复:
将 nvarchar 值“Internet Explorer 3 original”转换为数据类型 int 时转换失败

So I created this following simple stored procedure:

所以我创建了以下简单的存储过程:

CREATE PROCEDURE test
AS
BEGIN
    RETURN 'works!'
END
GO

I then wanted to execute it by firing the following statement:

然后我想通过触发以下语句来执行它:

EXEC test

Why am I getting the following error all the time?

为什么我总是收到以下错误?

Conversion failed when converting the varchar value 'works!' to data type int.

转换 varchar 值“有效!”时转换失败 到数据类型int。

Oh and btw, (when) is it necessary to have the GO-statement in the end of a stored procedure? I guess it takes no effect here since it will jump out of the procedure when I am returing my @out String.

哦,顺便说一句,(何时)有必要在存储过程的末尾使用 GO 语句?我想它在这里不起作用,因为当我返回@out String 时它会跳出程序。

回答by AdaTheDev

Using RETURNonly allows you to return an INTEGER code

使用RETURN仅允许您返回 INTEGER 代码

You either need to SELECT the value

您要么需要选择值

   CREATE PROCEDURE test
   AS
   BEGIN
       SELECT 'works!'
   END

or if you want to assign into a variable in the caller, use an OUTPUT parameter

或者如果您想分配给调用者中的变量,请使用 OUTPUT 参数

CREATE PROCEDURE test
    @outputVal VARCHAR(20) OUTPUT
AS
BEGIN
    SET @outputVal = 'works!'
END

DECLARE @val VARCHAR(20)
EXECUTE test @val OUTPUT