我正在尝试将其转换为使用CASE语句而不是IF语句,但我得到“Set附近的语法不正确”。
它在第一个SET:
WHEN 1 THEN
SET @firstOctet = CAST( SUBSTRING( @WorkingNullRouteIP, 1, @lastOctet - 1 ) )
DECLARE @lastOctet int,
@octetCount int,
@firstOctet int = -1,
@secondOctet int = -1,
@thirdOctet int = -1,
@fourthOctet int = -1
DECLARE @WorkingNullRouteIP varchar(50)
SET @WorkingNullRouteIP = @a_NullRouteIP
WHILE ( CHARINDEX('.',@WorkingNullRouteIP, @lastOctet ) > 0 )
BEGIN
SET @lastOctet = CHARINDEX('.',@WorkingNullRouteIP, @lastOctet )
SET @octetCount = @octetCount + 1
If @octetCount = 1
BEGIN
SET @firstOctet = CAST( SUBSTRING( @WorkingNullRouteIP, 1, @lastOctet - 1 ) )
END
If @octetCount = 2
BEGIN
SET @secondOctet = CAST( SUBSTRING( @WorkingNullRouteIP, 1, @lastOctet - 1 ) )
END
If @octetCount = 3
BEGIN
SET @thirdOctet = CAST( SUBSTRING( @WorkingNullRouteIP, 1, @lastOctet - 1 ) )
END
SET @WorkingNullRouteIP = SUBSTRING(@WorkingNullRouteIP, @lastOctet + 1)
SET @lastOctet = 1
END
-- Converting to this:
WHILE ( CHARINDEX('.',@WorkingNullRouteIP, @lastOctet ) > 0 )
BEGIN
SET @lastOctet = CHARINDEX('.',@WorkingNullRouteIP, @lastOctet )
SET @octetCount = @octetCount + 1
SELECT CASE @octetCount
WHEN 1 THEN
SET @firstOctet = CAST( SUBSTRING( @WorkingNullRouteIP, 1, @lastOctet - 1 ) )
WHEN 2 THEN
SET @secondOctet = CAST( SUBSTRING( @WorkingNullRouteIP, 1, @lastOctet - 1 ) )
WHEN 3 THEN
SET @thirdOctet = CAST( SUBSTRING( @WorkingNullRouteIP, 1, @lastOctet - 1 ) )
END
SET @WorkingNullRouteIP = SUBSTRING(@WorkingNullRouteIP, @lastOctet + 1)
SET @lastOctet = 1
END
答案 0 :(得分:4)
为什么不使用PARSENAME
所述的here功能DECLARE @WorkingNullRouteIP varchar(50) = '192.168.100.1';
DECLARE @firstOctet int = PARSENAME(@WorkingNullRouteIP,4),
@secondOctet int = PARSENAME(@WorkingNullRouteIP,3),
@thirdOctet int = PARSENAME(@WorkingNullRouteIP,2),
@fourthOctet int = PARSENAME(@WorkingNullRouteIP,1);
select
@firstOctet
,@secondOctet
,@thirdOctet
,@fourthOctet;
给予
----------- ----------- ----------- -----------
192 168 100 1