I am studying SQL, and I would like your advice, to see if this code is written properly, or better way to do it. This script create:
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
I assume you're going to use this outside of the database, presumably in .NET? In that case, I'd re-structure like this:
RETURN
, not PRINT
)Ip
with a static method int[] ToOctets(string ip)
that handles this for you. You'll use it as such: var octs = Ip.ToOctets("213.82.158.93")
I agree with Thomas, but do have a question: why are you storing the IP in 4 separate columns? If the whole point of the exercise is to track "black-listed IP addresses", then when would you ever need to examine just a piece of the IP address -- wouldn't you always be looking at the entire thing? So splitting/re-combining octets seems unnecessary. It causes you to write a lot of extra T-SQL too.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With