我需要生成具有指定长度的随机数字的字符串,所以我这样做:
ALTER PROCEDURE [dbo].[Generate Account]
AS
BEGIN
DECLARE @accountNumber VARCHAR(36)
DECLARE @acc_1 BIGINT
DECLARE @acc_2 BIGINT
DECLARE @acc_3 BIGINT
DECLARE @acc_4 BIGINT -- line 26
DECLARE @acc_5 BIGINT
DECLARE @acc_6 BIGINT
SET @acc_1 = 1000000-ceiling(rand()*100000) + datepart(ms, getdate())
SET @acc_2 = 1000000-ceiling(rand()*100000) + datepart(ms, getdate())
SET @acc_3 = 1000000-ceiling(rand()*100000) + datepart(ms, getdate())
SET @acc_4 = 1000000-ceiling(rand()*100000) + datepart(ms, getdate()) -- line 33
SET @acc_5 = 1000000-ceiling(rand()*100000) + datepart(ms, getdate())
SET @acc_6 = 1000000-ceiling(rand()*100000) + datepart(ms, getdate())
SET @accountNumber = CONVERT(VARCHAR(6), @acc_1) +
CONVERT(VARCHAR(6), @acc_2) +
CONVERT(VARCHAR(6), @acc_3) +
CONVERT(VARCHAR(6), @acc_4) +
CONVERT(VARCHAR(6), @acc_5) +
CONVERT(VARCHAR(6), @acc_6)
INSERT INTO [dbo].[account]
(
[identifier]
) VALUES (
@accountNumber
)
RETURN @accountNumber
END
但我收到错误:
为什么?我已经将Msg 8152, Level 16, State 14, Procedure Generate Account, Line 26 [Batch Start Line 2]
String or binary data would be truncated.
The statement has been terminated.Msg 248, Level 16, State 1, Procedure Generate Account, Line 33 [Batch Start Line 2]
The conversion of the varchar value '976547932115913127987338933646998655' overflowed an int column.
The 'Generate Account' procedure attempted to return a status of NULL, which is not allowed. A status of 0 will be returned instead.
@acc_X
从 INT 更改为 BIGINT,但我仍然收到此错误...
最佳答案
这里的问题是你的:
RETURN @accountNumber
在 SQL Server 中,当您尝试返回 36 位 varchar
时,存储过程只能返回 int
,并且 SQL Server 会隐式尝试将其转换为一个int
。
如果您需要插入的值,请将该行替换为简单的 select 语句:
SELECT @accountNumber AS AccountNumber
或
SELECT SCOPE_IDENTITY()
它应该可以工作。
如果您需要其他选项来从存储过程返回/输出值,请查看:
关于sql-server - SQL Server - varchar 值的转换溢出了 int 列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48366286/