限制SQL存储过程参数

时间:2018-05-04 08:01:48

标签: sql-server

我要求限制要传递到存储过程的参数中的位数。请考虑以下存储过程示例。

Create procedure Sp_test  
    @uniqueID1 varchar(100), 
    @uniqueID2 varchar(100),
    @uniqueID3 varchar(100) 
as 
Begin 
    select x,y,z 
    from  the table1 inner join table2 on a=b
    Where UniqueID in (@unitID1,@unitID2,@unitID3)
end

现在,当我传递参数值时,我必须检查其给定的位数,

exec sp_test '123456','456789','12356'

位数总是高于4或5位数。它不应少于4位数。我需要在存储过程中检查相同的内容。

注意:这里我可以使用单个参数传递多个唯一ID,但我在另一个应用程序中使用它,必须将其作为不同的参数传递。

请帮我解决。

1 个答案:

答案 0 :(得分:1)

也许就像使用IF..ELSE一样简单?

USE Sandbox;
GO

CREATE PROC Sample_sp @id1 varchar(5), @Id2 varchar(5) AS

    IF LEN(@id1) IN (4,5) AND LEN(@id2) IN (4,5) BEGIN

        PRINT 'Do your SP stuff here.';
        SELECT @id1, @Id2;
    END ELSE BEGIN
        RAISERROR('An ID must have a length of 4 or 5 characters.',11,1);
    END
GO

EXEC Sample_sp '12345', '6789'; --This will work, because both values are of length 4 or 5
GO
EXEC Sample_sp '12345', '678901'; --This will work, because the value would be truncated.
GO
EXEC Sample_sp '123456', '6789'; --This will work, because the value would be truncated.
GO
EXEC Sample_sp '1234', '6789'; --This will work, because both values are of length 4 or 5
GO
EXEC Sample_sp '123', '6789'; --Will fail, ID1 has a length of 3
GO

DROP PROC Sample_sp;

如果您不想截断(或者如果提供超过5个字符,则至少会失败),那么我建议将值增加到varchar(6)。它仍会导致截断,但考虑到你只关心6(或更多字符)的值,长度6和500都满足该要求;因此,如果传递了一个包含500个字符的参数,它将截断为varchar(6),然后仍然无法通过检查并导致错误。