我需要调用一个存储过程,给它一个报告id(int)并让它更新一个带有确认号(varchar)的报告表(确认#在存储过程中生成)并返回确认号(我将需要它将其返回到Web服务/网站)。
我的存储过程代码:
DECLARE PROCEDURE [dbo].[spUpdateConfirmation]
@ReportID int
AS
BEGIN
Declare @Confirmation varchar(30) = replace(replace(replace(convert(varchar(16),CURRENT_TIMESTAMP,120),'-',''),' ',''),':','')+convert(varchar(24),@ReportID)
PRINT @Confirmation
UPDATE Report
SET Confirmation = @Confirmation
WHERE ReportID = @ReportID;
RETURN @Confirmation
END
我对存储过程的调用:
execute [spUpdateConfirmation] 2
我在表格中确认已插入值,但收到此错误消息:
2013050219072
(1 row(s) affected)
Msg 248,Level 16,State 1,Procedure spUpdateConfirmation,Line 12
varchar值'2013050219072'的转换溢出了一个int列 'spUpdateConfirmation'过程尝试返回NULL状态,这是不允许的。将返回状态0。
问题:我做错了什么?
我理解溢出是什么,对于int来说值太大了,但我使用了转换为varchar
,插入到表列类型varchar(30)
我还在SQL中测试了这个语句,它运行正常:
print replace(replace(replace(convert(varchar(16),CURRENT_TIMESTAMP,120),'-',''),' ',''),':','')+convert(varchar(24),2)
返回:2013050219162
答案 0 :(得分:7)
RETURN仅允许整数值。具体来说,文档说明:
RETURN [integer_expression]
如果要返回varchar值,可以使用输出参数
CREATE PROCEDURE [dbo].[spUpdateConfirmation]
@ReportID int, @Confirmation varchar(30) output
AS
--BEGIN
SET @Confirmation = replace(replace(replace(convert(varchar(16),CURRENT_TIMESTAMP,120),'-',''),' ',''),':','')+convert(varchar(24),@ReportID)
--PRINT @Confirmation
UPDATE Report
SET Confirmation = @Confirmation
WHERE ReportID = @ReportID;
--RETURN @Confirmation
--END
GO
像这样被召唤
declare @reportID int; -- set @reportID
declare @confirmation varchar(30);
exec [dbo].[spUpdateConfirmation] @reportID, @confirmation output;
-- @confirmation now contains the value set from the SP call above
如果从C#调用此选项,则更简单的选项是将输出选择为单行单列结果并使用SqlCommand.ExecuteScalar
,例如
CREATE PROCEDURE [dbo].[spUpdateConfirmation]
@ReportID int
AS
--BEGIN
DECLARE @Confirmation varchar(30);
SET @Confirmation = replace(replace(replace(convert(varchar(16),CURRENT_TIMESTAMP,120),'-',''),' ',''),':','')+convert(varchar(24),@ReportID)
--PRINT @Confirmation
SET NOCOUNT ON; -- prevent rowcount messages
UPDATE Report
SET Confirmation = @Confirmation
WHERE ReportID = @ReportID;
--RETURN @Confirmation
SET NOCOUNT OFF; -- re-enable for the following select
SELECT @Confirmation; -- this is the value you get
--END
GO