Hi, I am studing SQL, and I would like your advice, to see if my code is written properly, or better way to do it. This script create:
- a table to store IPs address that are Black Listed
- a sproc to allow spitting an IP address in 4 octet
a SPROC that allow to check if a IP is Black Listed or not Please let me know! thanks!
-- Black Listed Table CREATE TABLE UtlBlacklistedIPs ( octet1 TINYINT, octet2 TINYINT, octet3 TINYINT, octet4 TINYINT );
1 SPROC
-- Convert an IP address in 4 octet for db storing
CREATE PROCEDURE dbo.storeIPoctetsv1
@ip CHAR(15)
AS
BEGIN
SET NOCOUNT ON
INSERT UtlBlacklistedIPs(octet1, octet2, octet3, octet4)
SELECT
CONVERT(TINYINT, PARSENAME(@ip, 4)),
CONVERT(TINYINT, PARSENAME(@ip, 3)),
CONVERT(TINYINT, PARSENAME(@ip, 2)),
CONVERT(TINYINT, PARSENAME(@ip, 1))
END
2 SPROC
-- SPROC check if an IP address has been black listed
CREATE PROCEDURE dbo.sprocCheckIp
@ip CHAR(15)
AS
BEGIN
SET NOCOUNT ON
DECLARE
@octet1 tinyint,
@octet2 tinyint,
@octet3 tinyint,
@octet4 tinyint;
SET @octet1 = CONVERT(tinyint, PARSENAME(@ip, 4));
SET @octet2 = CONVERT(tinyint, PARSENAME(@ip, 3));
SET @octet3 = CONVERT(tinyint, PARSENAME(@ip, 2));
SET @octet4 = CONVERT(tinyint, PARSENAME(@ip, 1));
IF EXISTS (
SELECT octet1, octet2, octet3, octet4
FROM UtlBlacklistedIPs
WHERE
octet1 =@octet1
AND octet2 =@octet2
AND octet3 =@octet3
AND octet4 =@octet4
)
BEGIN
PRINT 'Ip: '+@ip+' is black listed'
END
ELSE
BEGIN
PRINT 'Ip: '+@ip+' is NOT black listed'
END
END
Some values
-- Insert dummy values
DECLARE @i INT
SET @i = 0
WHILE @i < 2000
BEGIN
EXEC dbo.storeIPoctetsv1 @ip = '204.71.34.21'
EXEC dbo.storeIPoctetsv1 @ip = '12.38.145.32'
EXEC dbo.storeIPoctetsv1 @ip = '127.0.0.1'
SET @i = @i + 1
END
Use the SPROC
-- Use SPROc
EXEC dbo.sprocCheckIp '125.254.125.111' -- NOT black listed Ip
EXEC dbo.sprocCheckIp '204.71.34.21' -- black listed Ip