sql table 只插入随机id的第一个字符

Only the first character of random id is inserted to the sql table

我正在对 table 进行批量插入。我有多个触发器可以将多个列从批量插入插入到不同的 table。我生成长度为 25 的字母数字字符作为 id。我创建了一个函数来执行此操作,在我需要 @ID 列的值的地方调用此函数。但我只插入了那些随机字符串字符的第一位数字。

在我调用函数的地方触发

 IF NOT EXISTS(SELECT * FROM CHEMICAL WHERE Chemical_Name = @Chemical_Name)
    BEGIN
        INSERT INTO CHEMICAL(Chemical_ID, Chemical_Name, CAS_Number,EHS,TPQ_Pounds,RQ_Pounds,last_updated)
        VALUES(dbo.SDS_GENERATE_ID(), @Chemical_Name,@CAS_Number, @EHS,@TPQ_Pounds,@RQ_Pounds,getdate())
    END 

函数SDS_GENERATE_ID

CREATE FUNCTION SDS_GENERATE_ID()
RETURNS VARCHAR
AS
BEGIN

DECLARE @r varchar(25)
SELECT @r = coalesce(@r, '') + n
FROM (SELECT top 25 
CHAR(number) n FROM
master..spt_values
WHERE type = 'P' AND 
(number between ascii(0) and ascii(9)
or number between ascii('A') and ascii('Z')
or number between ascii('a') and ascii('z'))
ORDER BY (select * from MyRAND)) a
return @r
   END;
   GO

MyRand VIEW 因为我不能在 udfs 中使用 NEWID()

CREATE VIEW [dbo].[MyRAND]
AS
select newid() as randID
GO

感谢任何帮助,并提前致谢。

CREATE FUNCTION SDS_GENERATE_ID()
RETURNS VARCHAR

您需要指定长度,否则您最终会收到单个字符

当前形式的函数 returns 仅低于值..

0

当通过如下指定长度进行修改时 returns

CREATE FUNCTION SDS_GENERATE_ID()
RETURNS VARCHAR(25)

给予

01234656789..

您尚未在函数 return 中 指定字符长度 类型:

alter FUNCTION SDS_GENERATE_ID()
RETURNS VARCHAR(20)
AS
BEGIN

DECLARE @r varchar(25)
SELECT @r = coalesce(@r, '') + n
FROM (SELECT top 25 
CHAR(number) n FROM
master..spt_values
WHERE type = 'P' AND 
(number between ascii(0) and ascii(9)
or number between ascii('A') and ascii('Z')
or number between ascii('a') and ascii('z'))
ORDER BY (select id from employee)) a
return @r
   END;
   GO

注意:在上面return中替换您需要的长度,键入