如果长度不等于,则T-SQL抛出错误

时间:2017-09-28 08:28:23

标签: sql-server tsql

我正在尝试为SQL Server 2016创建一个存储过程,以便将MD5哈希值插入到表中。我想检查输入的长度,所以如果散列不是32(或34个字符),我可以抛出错误。

CREATE PROCEDURE dbo.usp_insert_imagestore
    @HashStr NVARCHAR(MAX),
    @NewId BIGINT OUT
AS
BEGIN
    SET NOCOUNT ON;

    IF LEFT(@HashStr, 2) = '0x' 
    BEGIN
        IF LEN(@HashStr) <> 34
        BEGIN
            ;THROW 50001, 'The HASH string must be a valid MD5 HASH!', 1;
        END
    ELSE
        IF LEN(@HashStr) <> 32
        BEGIN
            ;THROW 50002, 'The HASH string must be a valid MD5 HASH!', 1;
        END
    END
...
END
GO

这里的问题是错误按摩不会激活,即使我指定少于或多于32或34个字符。我错过了什么?

SSMS中的代码是

DECLARE @NewId bigint
EXECUTE [dbo].[usp_insert_imagestore] 
  '7815696ECBF1C96E6894B779456D330E000000000000000000000000'
  ,@NewId OUTPUT
GO

select * from ImageStore;

这应该引发错误,不应该吗?

3 个答案:

答案 0 :(得分:2)

ELSE@HashStr开头并且此变量的长度等于34时,0x将“触发”。您必须将代码更改为:

CREATE PROCEDURE dbo.usp_insert_imagestore
    @HashStr NVARCHAR(MAX),
    @NewId BIGINT OUT
AS
BEGIN
    SET NOCOUNT ON;

    IF LEFT(@HashStr, 2) = '0x' 
    BEGIN
        IF LEN(@HashStr) <> 34
        BEGIN
            ;THROW 50001, 'The HASH string must be a valid MD5 HASH!', 1;
        END
    END /*<-- Add this*/
    ELSE
    BEGIN /*<-- Add this*/
        IF LEN(@HashStr) <> 32
        BEGIN
            ;THROW 50002, 'The HASH string must be a valid MD5 HASH!', 1;
        END
    END
...
END
GO

答案 1 :(得分:0)

DECLARE @HashStr NVARCHAR(100) = '0x12345678901234567890123456789012';

IF LEFT(@HashStr, 2) = '0x' AND LEN(@HashStr) <> 34 
  BEGIN
    ;THROW 50001, 'The HASH string must be a valid MD5 HASH!', 1;
  END
ELSE IF LEFT(@HashStr, 2) != '0x' AND LEN(@HashStr) <> 32
  BEGIN
    ;THROW 50002, 'The HASH string must be a valid MD5 HASH!', 1;
  END

答案 2 :(得分:0)

您需要ENDELSEBEGINELSE,否则IF LEN(@HashStr) <> 34适用于{{1}}