Related
I have the following table with following data as
Tab1
FutureMISBoundaryVersion CurrentMISBoundaryVersion FutureHAMBoundaryVersion CurrentHAMBoundaryVersion
2:21,5:50,4:55,7:80,9:33 2:12,5:40,4:35,7:60,9:87 2:52,5:90,4:75,7:30,9:57 2:42,5:60,4:95,7:70,9:37
This key value pair has to be split into and the value of each key has to be inserted into another table in the following fashion
FutureMIS-OAKVersion |FutureMIS-HAMVersion |FutureMIS-DURVersion | FutureMIS-BURVersion| FutureMIS-YRTVersion |DeviceMIS-OAKVersion|DeviceMIS-HAMVersion |DeviceMIS-DURVersion| DeviceMIS-BURVersion| DeviceMIS-YRTVersion
33 | 80 | 21 | 55 | 50 | 87 | 60 |12 |35 | 40
i,e: when it finds column 'FutureMISBoundaryVersion' in tab1 then its value
'2:21,5:50,4:55,7:80,9:33' will be split and its value is inserted in such a way that the corresponding value of key 2 i,e:21 will be inserted into FutureMIS-DURVersion column.
Similarly key 5's value 50 will be inserted into FutureMIS-BURVersion column and so on for other keys
when it finds column 'CurrentMISBoundaryVersion' then
'2:12,5:40,4:35,7:60,9:87' will be split and its value is inserted in such a way that the corresponding value of key 2 i,e:12 will be inserted into CurrentMIS-DURVersion column similarly key 5's 40 value will be inserted into DeviceMIS-YRTVersion column and so on for other columns of the source table.
The table structure may extend as I have shown only 4 source table column but logic for all the columns remain same
Very funky requirements to be honest.
Please note solution below will work only in SQL Server 2016+ as I'm using JSON to parse the data. However you can write your own parser, in this case code will work in almost all versions of SQL Server.
Parse function:
CREATE FUNCTION dbo.ParseIt(#Type NVARCHAR(255),#Value NVARCHAR(MAX))
RETURNS #Parsed TABLE (Code NVARCHAR(255),Value NVARCHAR(255))
AS
BEGIN
INSERT INTO #Parsed(Code,Value)
SELECT #Type + '-' + m.Code + 'Version' AS [Code],p.[1] AS [Value]
FROM (
SELECT j.[key] AS [ID],i.[key],i.value
FROM OPENJSON('["' + REPLACE(#Value,',','","') + '"]') j
CROSS APPLY OPENJSON('[' + REPLACE(j.[value],':',',') + ']') i
) a
PIVOT(MAX(a.value) FOR a.[key] IN ([0],[1])) p
INNER JOIN ( VALUES
(2,'DUR')
,(4,'BUR')
,(5,'YRT')
,(7,'HAM')
,(9,'OAK')
) m(ID, Code) ON m.ID = p.[0]
;
RETURN;
END
Initial data:
DECLARE #Table TABLE (FutureMISBoundaryVersion NVARCHAR(MAX), CurrentMISBoundaryVersion NVARCHAR(MAX),FutureHAMBoundaryVersion NVARCHAR(MAX),CurrentHAMBoundaryVersion NVARCHAR(MAX));
INSERT INTO #Table(FutureMISBoundaryVersion,CurrentMISBoundaryVersion,FutureHAMBoundaryVersion,CurrentHAMBoundaryVersion)VALUES
('2:21,5:50,4:55,7:80,9:33','2:12,5:40,4:35,7:60,9:87','2:52,5:90,4:75,7:30,9:57','2:42,5:60,4:95,7:70,9:37')
;
The code:
SELECT COALESCE(p.[FutureMIS-OAKVersion],'') AS [FutureMIS-OAKVersion]
,COALESCE(p.[FutureMIS-HAMVersion],'') AS [FutureMIS-HAMVersion]
,COALESCE(p.[FutureMIS-DURVersion],'') AS [FutureMIS-DURVersion]
,COALESCE(p.[FutureMIS-BURVersion],'') AS [FutureMIS-BURVersion]
,COALESCE(p.[FutureMIS-YRTVersion],'') AS [FutureMIS-YRTVersion]
,COALESCE(p.[DeviceMIS-OAKVersion],'') AS [DeviceMIS-OAKVersion]
,COALESCE(p.[DeviceMIS-HAMVersion],'') AS [DeviceMIS-HAMVersion]
,COALESCE(p.[DeviceMIS-DURVersion],'') AS [DeviceMIS-DURVersion]
,COALESCE(p.[DeviceMIS-BURVersion],'') AS [DeviceMIS-BURVersion]
,COALESCE(p.[DeviceMIS-YRTVersion],'') AS [DeviceMIS-YRTVersion]
FROM (
SELECT f.Code,f.Value FROM #Table t CROSS APPLY dbo.ParseIt('FutureMIS',t.FutureMISBoundaryVersion) f
UNION ALL
SELECT f.Code,f.Value FROM #Table t CROSS APPLY dbo.ParseIt('DeviceMIS',t.CurrentMISBoundaryVersion) f
) a
PIVOT(MAX(a.Value) FOR a.Code IN ([DeviceMIS-BURVersion],[DeviceMIS-DURVersion],[DeviceMIS-HAMVersion],[DeviceMIS-OAKVersion]
,[DeviceMIS-YRTVersion],[FutureMIS-BURVersion],[FutureMIS-DURVersion],[FutureMIS-HAMVersion],[FutureMIS-OAKVersion]
,[FutureMIS-YRTVersion])) p
;
The following query will parse the comma separated string 2:21,5:50,4:55,7:80,9:33 into individual component 2:21, 5:30 etc. From there you can use similar method to extract bb from aa:bb.
Since the key-value pair is in format aa:bb, you can use datepart(hour, 'aa:bb') and datepart(minute, 'aa:bb') to extract aa and bb
; with
Tab1 as
(
select val = '2:21,5:50,4:55,7:80,9:33'
)
select t.*, k1.k, k2.k, k3.k, k4.k, k5.k
from Tab1 t
cross apply
(
select i = charindex(',', t.val),
k = substring(t.val, 1, charindex(',', t.val + ',', 1) - 1)
) k1
cross apply
(
select i = charindex(',', t.val, k1.i + 1),
k = substring(t.val, k1.i + 1, charindex(',', t.val + ',', k1.i + 1) - k1.i - 1)
) k2
cross apply
(
select i = charindex(',', t.val, k2.i + 1),
k = substring(t.val, k2.i + 1, charindex(',', t.val + ',', k2.i + 1) - k2.i - 1)
) k3
cross apply
(
select i = charindex(',', t.val, k3.i + 1),
k = substring(t.val, k3.i + 1, charindex(',', t.val + ',', k3.i + 1) - k3.i - 1)
) k4
cross apply
(
select i = charindex(',', t.val, k4.i + 1),
k = substring(t.val, k4.i + 1, charindex(',', t.val + ',', k4.i + 1) - k4.i - 1)
) k5
This is a pain in SQL Server. You can do this with recursive CTEs:
with cte as (
select convert(varchar(max), left(FutureMISBoundaryVersion, charindex(',', FutureMISBoundaryVersion) - 1)) as FutureMISBoundaryVersion,
convert(varchar(max), left(CurrentMISBoundaryVersion, charindex(',', CurrentMISBoundaryVersion) - 1)) as CurrentMISBoundaryVersion,
convert(varchar(max), left(FutureHAMBoundaryVersion, charindex(',', FutureHAMBoundaryVersion) - 1)) as FutureHAMBoundaryVersion,
convert(varchar(max), left(CurrentHAMBoundaryVersion, charindex(',', FutureMISBoundaryVersion) - 1)) as CurrentHAMBoundaryVersion,
stuff(FutureMISBoundaryVersion, 1, charindex(',', FutureMISBoundaryVersion), '') + ',' as FutureMISBoundaryVersion_rest,
stuff(CurrentMISBoundaryVersion, 1, charindex(',', CurrentMISBoundaryVersion), '') + ',' as CurrentMISBoundaryVersion_rest,
stuff(FutureHAMBoundaryVersion, 1, charindex(',', FutureHAMBoundaryVersion), '') + ',' as FutureHAMBoundaryVersion_rest,
stuff(CurrentHAMBoundaryVersion, 1, charindex(',', CurrentHAMBoundaryVersion), '') + ',' as CurrentHAMBoundaryVersion_rest,
1 as lev
from t
union all
select convert(varchar(max), left(FutureMISBoundaryVersion_rest, charindex(',', FutureMISBoundaryVersion_rest) - 1)) as FutureMISBoundaryVersion,
convert(varchar(max), left(CurrentMISBoundaryVersion_rest, charindex(',', CurrentMISBoundaryVersion_rest) - 1)) as CurrentMISBoundaryVersion,
convert(varchar(max), left(FutureHAMBoundaryVersion_rest, charindex(',', FutureHAMBoundaryVersion_rest) - 1)) as FutureHAMBoundaryVersion,
convert(varchar(max), left(CurrentHAMBoundaryVersion_rest, charindex(',', CurrentHAMBoundaryVersion_rest) - 1)) as CurrentHAMBoundaryVersion,
stuff(FutureMISBoundaryVersion_rest, 1, charindex(',', FutureMISBoundaryVersion_rest), '') as FutureMISBoundaryVersion_rest,
stuff(CurrentMISBoundaryVersion_rest, 1, charindex(',', CurrentMISBoundaryVersion_rest), '') as CurrentMISBoundaryVersion_rest,
stuff(FutureHAMBoundaryVersion_rest, 1, charindex(',', FutureHAMBoundaryVersion_rest), '') as FutureHAMBoundaryVersion_rest,
stuff(CurrentHAMBoundaryVersion_rest, 1, charindex(',', CurrentHAMBoundaryVersion_rest), '') as CurrentHAMBoundaryVersion_rest,
lev + 1
from cte
where FutureMISBoundaryVersion_rest like '%,%'
)
select FutureMISBoundaryVersion, CurrentMISBoundaryVersion, FutureHAMBoundaryVersion, CurrentHAMBoundaryVersion, lev
from cte;
Here is a db<>fiddle.
I am writing a query that roughly has this structure:
SELECT Name, <calculated-valued> as Version FROM <tables>
This calculated value needs to work like so: I have a varchar column 'Name' that could contain something like 'ABC' and I want to convert each letter into ASCII, and append them back together to form '65.66.67' in this example. (An empty string should return '0') Is there any way to do this?
My approach wasn't very good, but up to 5 characters I could do the following:
SELECT
CASE WHEN LEN(Name) = 0 THEN '0'
ELSE CAST(ASCII(SUBSTRING(Name, 1, 1)) as varchar(max)) +
CASE WHEN LEN(Name) = 1 THEN ''
ELSE '.' + CAST(ASCII(SUBSTRING(Name, 2, 1)) as varchar(max)) +
CASE WHEN LEN(Name) = 2 THEN ''
ELSE '.' + CAST(ASCII(SUBSTRING(Name, 3, 1)) as varchar(max)) +
CASE WHEN LEN(Name) = 3 THEN ''
ELSE '.' + CAST(ASCII(SUBSTRING(Name, 4, 1)) as varchar(max)) +
CASE WHEN LEN(Name) = 4 THEN ''
ELSE '.' + CAST(ASCII(SUBSTRING(Name, 5, 1)) as varchar(max))
END
END
END
END
END AS MyColumn
FROM <tables>
Is there a better way to do this? Ideally a method that can take any length of string?
Either that or can I cast letters into a hierarchyid datatype? I need to create things like 1/2/a/bc/4// or whatever, but hierarchyid doesn't support that. So instead I'm trying to convert it to 1/2/97/98.99/4/0 so I can convert and maintain the correct order. This column is only used for sorting.
Thanks for any help!
One method is a recursive CTE:
with cte as (
select Name, 1 as lev
cast(ascii(substring(name, 1, 1)) as varchar(max)) as ascii_name
from t
union all
select Name, lev + 1,
ascii_name + '.' + cast(ascii(substring(name, lev + 1, 1)) as varchar(max))
from cte
where len(Name) > lev
)
select Name, ascii_name
from cte;
Another option is with an ad-hoc tally table and a CROSS APPLY
Declare #YourTable table (Name varchar(25))
Insert Into #YourTable values
('ABC'),
('Jack'),
('Jill'),
('')
Select A.Name
,Version = isnull(B.String,'0')
From #YourTable A
Cross Apply (
Select String=Stuff((Select '.' +cast(S as varchar(5))
From (Select Top (len(A.Name))
S=ASCII(substring(A.Name,Row_Number() Over (Order By (Select NULL)),1))
From master..spt_values ) S
For XML Path ('')),1,1,'')
) B
Returns
Name String
ABC 65.66.67
Jack 74.97.99.107
Jill 74.105.108.108
0
I have data as below
98-45.3A-22
104-44.0A-23
00983-29.1-22
01757-42.5A-22
04968-37.3A2-23
Output Looking for output as below in SQL Server
00098-BA45.3A-IN-22
00104-BA44.0A-IN-23
00983-BA29.1-IN-22
01757-BA42.5A-IN-22
04968-BA37.3A2-IN-23
I splitted parts to cope with tricky data templates. This should work even with non-dash-2-digit tail:
WITH Src AS
(
SELECT * FROM (VALUES
('98-45.3A-22'),
('104-44.0A-23'),
('00983-29.1-22'),
('01757-42.5A-22'),
('04968-37.3A2-23')
) T(X)
), Parts AS
(
SELECT *,
RIGHT('00000'+SUBSTRING(X, 1, CHARINDEX('-',X, 1)-1),5) Front,
'BA'+SUBSTRING(X, CHARINDEX('-',X, 1)+1, 2) BA,
SUBSTRING(X, PATINDEX('%.%',X), LEN(X)-CHARINDEX('-', REVERSE(X), 1)-PATINDEX('%.%',X)+1) P,
SUBSTRING(X, LEN(X)-CHARINDEX('-', REVERSE(X), 1)+1, LEN(X)) En
FROM Src
)
SELECT Front+'-'+BA+P+'-IN'+En
FROM Parts
It returns:
00098-BA45.3A-IN-22
00104-BA44.0A-IN-23
00983-BA29.1-IN-22
01757-BA42.5A-IN-22
04968-BA37.3A2-IN-23
Try this,
DECLARE #String VARCHAR(100) = '98-45.3A-22'
SELECT ISNULL(REPLICATE('0',6 - CHARINDEX('-',#String)),'') -- Add leading Zeros
+ STUFF(
STUFF(#String,CHARINDEX('-',#String),1,'-BA'), -- Add 'BA'
CHARINDEX('-',#String,CHARINDEX('-',#String)+1)+2, -- 2 additional for the character 'BA'
1,'-IN') -- Add 'IN'
What if I have more than 6 digit number before first hyphen and want to remove the leading zeros to make it 6 digits.
DECLARE #String VARCHAR(100) = '0000098-45.3A-22'
SELECT CASE WHEN CHARINDEX('-',#String) <= 6
THEN ISNULL(REPLICATE('0',6 - CHARINDEX('-',#String)),'') -- Add leading Zeros
+ STUFF(
STUFF( #String,CHARINDEX('-',#String),1,'-BA'), -- Add 'BA'
CHARINDEX('-',#String,CHARINDEX('-',#String)+1)+2, -- 2 additional for the character 'BA'
1,'-IN') -- Add 'IN'
ELSE STUFF(
STUFF(
STUFF(#String,CHARINDEX('-',#String),1,'-BA'), -- Add 'BA'
CHARINDEX('-',#String,CHARINDEX('-',#String)+1)+2, -- 2 additional for the character 'BA'
1,'-IN'), -- Add 'IN'
1, CHARINDEX('-',#String) - 6, '' -- remove extra leading Zeros
)
END
Making assumptions that the format is consistent (e.g. always ends with "-" + 2 characters....)
DECLARE #Data TABLE (Col1 VARCHAR(100))
INSERT #Data ( Col1 )
SELECT Col1
FROM (
VALUES ('98-45.3A-22'), ('104-44.0A-23'),
('00983-29.1-22'), ('01757-42.5A-22'),
('04968-37.3A2-23')
) x (Col1)
SELECT RIGHT('0000' + LEFT(Col1, CHARINDEX('-', Col1) - 1), 5)
+ '-BA' + SUBSTRING(Col1, CHARINDEX('-', Col1) + 1, CHARINDEX('.', Col1) - CHARINDEX('-', Col1))
+ SUBSTRING(Col1, CHARINDEX('.', Col1) + 1, LEN(Col1) - CHARINDEX('.', Col1) - 3)
+ '-IN-' + RIGHT(Col1, 2)
FROM #Data
It's not ideal IMO to do this string manipulation all the time in SQL. You could shift it out to your presentation layer, or store the pre-formatted value in the db to save the cost of this every time.
Use REPLICATE AND CHARINDEX:
Replicate: will repeat given character till reach required count specify in function
CharIndex: Finds the first occurrence of any character
Declare #Data AS VARCHAR(50)='98-45.3A-22'
SELECT REPLICATE('0',6-CHARINDEX('-',#Data)) + #Data
SELECT
SUBSTRING
(
(REPLICATE('0',6-CHARINDEX('-',#Data)) +#Data)
,0
,6
)
+'-'+'BA'+ CAST('<x>' + REPLACE(#Data,'-','</x><x>') + '</x>' AS XML).value('/x[2]','varchar(max)')
+'-'+ 'IN'+ '-' + CAST('<x>' + REPLACE(#Data,'-','</x><x>') + '</x>' AS XML).value('/x[3]','varchar(max)')
In another way by using PARSENAME() you can use this query:
WITH t AS (
SELECT
PARSENAME(REPLACE(REPLACE(s, '.', '###'), '-', '.'), 3) AS p1,
REPLACE(PARSENAME(REPLACE(REPLACE(s, '.', '###'), '-', '.'), 2), '###', '.') AS p2,
PARSENAME(REPLACE(REPLACE(s, '.', '###'), '-', '.'), 1) AS p3
FROM yourTable)
SELECT RIGHT('00000' + p1, 5) + '-BA' + p2 + '-IN-' + p3
FROM t;
I have a table which stores a ID, Name, Code, IPLow, IPHigh such as:
1, Lucas, 804645, 192.130.1.1, 192.130.1.254
2, Maria, 222255, 192.168.2.1, 192.168.2.254
3, Julia, 123456, 192.150.3.1, 192.150.3.254
Now, if I have an IP address 192.168.2.50, how can I retrieve the matching record?
Edit
Based on Gordon's answer (which I'm getting compilation errors) this is what I have:
select PersonnelPC.*
from (select PersonnelPC.*,
(
cast(parsename(iplow, 4)*1000000000 as decimal(12, 0)) +
cast(parsename(iplow, 3)*1000000 as decimal(12, 0)) +
cast(parsename(iplow, 2)*1000 as decimal(12, 0)) +
(parsename(iplow, 1))
) as iplow_decimal,
(
cast(parsename(iphigh, 4)*1000000000 as decimal(12, 0)) +
cast(parsename(iphigh, 3)*1000000 as decimal(12, 0)) +
cast(parsename(iphigh, 2)*1000 as decimal(12, 0)) +
(parsename(iphigh, 1))
) as iphigh_decimal
from PersonnelPC
) PersonnelPC
where 192168002050 between iplow_decimal and iphigh_decimal;
but this gives me an error:
Msg 8115, Level 16, State 2, Line 1
Arithmetic overflow error converting expression to data type int.
Any ideas?
Painfully. SQL Server has lousy string manipulation functions. It does, however, offer parsename(). This approach converts the IP address to a large decimal value for the comparison:
select t.*
from (select t.*,
(cast(parsename(iplow, 4)*1000000000.0 as decimal(12, 0)) +
cast(parsename(iplow, 3)*1000000.0 as decimal(12, 0)) +
cast(parsename(iplow, 2)*1000.0 as decimal(12, 0)) +
cast(parsename(iplow, 1) as decimal(12, 0))
) as iplow_decimal,
(cast(parsename(iphigh, 4)*1000000000.0 as decimal(12, 0)) +
cast(parsename(iphigh, 3)*1000000.0 as decimal(12, 0)) +
cast(parsename(iphigh, 2)*1000.0 as decimal(12, 0)) +
cast(parsename(iphigh, 1) as decimal(12, 0))
) as iphigh_decimal
from t
) t
where 192168002050 between iplow_decimal and iphigh_decimal;
I should note that IP addresses are often stored in the database as the 4-byte unsigned integers. This makes comparisons much easier . . . although you need complicated logic (usually wrapped in a function) to convert the values to a readable format.
Try this simple way checking range
DECLARE #IP NVARCHAR(30)='192.168.500.1'
SELECT * FROM
Branches
WHERE
CAST (PARSENAME(#IP,4) AS INT)>=CAST(PARSENAME(IPLow,4) AS INT) AND CAST(PARSENAME(#IP,3) AS INT)>=CAST(PARSENAME(IPLow,3) AS INT) AND CAST(PARSENAME(#IP,2) AS INT)>=CAST(PARSENAME(IPLow,2) AS INT) AND CAST(PARSENAME(#IP,1) AS INT)>=CAST(PARSENAME(IPLow,1) AS INT)
AND
CAST(PARSENAME( #IP,4) AS INT) <= CAST(PARSENAME(IPHigh ,4) AS INT) AND CAST(PARSENAME(#IP ,3) AS INT) <=CAST(PARSENAME(IPHigh ,3) AS INT) AND CAST(PARSENAME(#IP ,2) AS INT) <=CAST(PARSENAME(IPHigh ,2) AS INT) AND CAST(PARSENAME(#IP ,1) AS INT)<=CAST(PARSENAME(IPHigh ,1) AS INT)
AS Per #Ed Haper Comment Cast is needed.
With this function you can transform any IP address to a form where each part has 3 digits. With this you could do a normal alphanumeric compare. if you want you could return BIGINT too...
CREATE FUNCTION dbo.IPWidth3(#IP VARCHAR(100))
RETURNS VARCHAR(15)
BEGIN
DECLARE #RetVal VARCHAR(15);
WITH Splitted AS
(
SELECT CAST('<x>' + REPLACE(#IP,'.','</x><x>') + '</x>' AS XML) AS IPSplitted
)
SELECT #RetVal = STUFF(
(
SELECT '.' + REPLACE(STR(Part.value('.','int'),3),' ','0')
FROM Splitted.IPSplitted.nodes('/x') AS One(Part)
FOR XML PATH('')
),1,1,'')
FROM Splitted;
RETURN #RetVal;
END
GO
DECLARE #IP VARCHAR(100)='192.43.2.50';
SELECT dbo.IPWidth3(#IP);
The result
192.043.002.050
To reflect Ed Harper's comment here the same function returning a DECIMAL(12,0):
CREATE FUNCTION dbo.IP_as_Number(#IP VARCHAR(100))
RETURNS DECIMAL(12,0)
BEGIN
DECLARE #RetVal DECIMAL(12,0);
WITH Splitted AS
(
SELECT CAST('<x>' + REPLACE(#IP,'.','</x><x>') + '</x>' AS XML) AS IPSplitted
)
SELECT #RetVal =
CAST((
SELECT REPLACE(STR(Part.value('.','int'),3),' ','0')
FROM Splitted.IPSplitted.nodes('/x') AS One(Part)
FOR XML PATH('')
) AS DECIMAL(12,0))
FROM Splitted;
RETURN #RetVal;
END
GO
DECLARE #IP VARCHAR(100)='192.43.2.50';
SELECT dbo.IP_as_Number(#IP);
Use below to fetch the ipLow / IPHigh in 4 columns. You can use those columns to compare Ips.
DECLARE#ip VARCHAR(50)='192.168.0.81'
SELECT (SUBSTRING((#ip), 0,
patindex('%.%',
(#ip))))
,
substring((REPLACE(#ip, (SUBSTRING((#ip), 0,
patindex('%.%',
(#ip)) + 1)),
'')),
0,
patindex('%.%',
((REPLACE(#ip, (SUBSTRING((#ip), 0,
patindex('%.%',
(#ip)) + 1)),
''))))),
SUBSTRING((SUBSTRING(#ip, LEN((SUBSTRING((#ip), 0,
patindex('%.%',
(#ip))))) + 2 + LEN(substring((REPLACE(#ip, (SUBSTRING((#ip), 0,
patindex('%.%',
(#ip)) + 1)),
'')),
0,
patindex('%.%',
((REPLACE(#ip, (SUBSTRING((#ip), 0,
patindex('%.%',
(#ip)) + 1)),
'')))))) + 1,
LEN(#IP) - 1 - LEN(reverse(SUBSTRING(reverse(#ip), 0,
patindex('%.%',
reverse(#ip))))))), 0,
PATINDEX('%.%',
(SUBSTRING(#ip, LEN((SUBSTRING((#ip), 0,
patindex('%.%',
(#ip))))) + 2 + LEN(substring((REPLACE(#ip, (SUBSTRING((#ip), 0,
patindex('%.%',
(#ip)) + 1)),
'')),
0,
patindex('%.%',
((REPLACE(#ip, (SUBSTRING((#ip), 0,
patindex('%.%',
(#ip)) + 1)),
'')))))) + 1,
LEN(#IP) - 1 - LEN(reverse(SUBSTRING(reverse(#ip), 0,
patindex('%.%',
reverse(#ip))))))
))),
reverse(SUBSTRING(reverse(#ip), 0,
patindex('%.%',
reverse(#ip))))
Consider something like this example to convert the address into a number.
CREATE FUNCTION dbo.IPAddressAsNumber (#IPAddress AS varchar(15))
RETURNS bigint
BEGIN
RETURN
CONVERT (bigint,
CONVERT(varbinary(1), CONVERT(int, PARSENAME(#IPAddress, 4))) +
CONVERT(varbinary(1), CONVERT(int, PARSENAME(#IPAddress, 3))) +
CONVERT(varbinary(1), CONVERT(int, PARSENAME(#IPAddress, 2))) +
CONVERT(varbinary(1), CONVERT(int, PARSENAME(#IPAddress, 1))) )
END
and with that you could use standard operators like BETWEEN to find rows within the range you have in the table
DECLARE #t table (ID int, Name varchar(50), Code int, IPLow varchar(15), IPHigh varchar(15))
INSERT INTO #t VALUES
(1, 'Lucas', 804645, '192.130.1.1', '192.130.1.254'),
(2, 'Maria', 222255, '192.168.2.1', '192.168.2.254'),
(3, 'Julia', 123456, '192.150.3.1', '192.150.3.254')
SELECT * FROM #t
WHERE dbo.IPAddressAsNumber('192.168.2.50')
BETWEEN dbo.IPAddressAsNumber(IPLow) AND dbo.IPAddressAsNumber(IPHigh)
The scheme essentially uses PARSENAME to isolate each part of the address, converts each part into a SQL binary string, concatenating the strings together to get a single SQL binary string representing the address, and shows the result as a bigint.
In a textual representation of hexadecimal values think of this as smashing the 4 parts together 192(0xC0) + 168(0xA8) + 2(0x02) + 50(0x32) into 0xC0A80232. When you turn that combined string into its binary digits (0s and 1s) you would end up with something that could be thought of as the address in a binary form used by the network stack in address routing and subnet masking tables. When you turn that into a number in the form of an unsigned integer (or in this case a bigint) you get 3232236082.
Interestingly this scheme gives you a "number" that can be used in place of the original address in lots of ways. You can for example ping the number 2130706433 instead of the address 127.0.0.1 -- the name resolver in Windows will convert it similarly to how DNS is used to find the address of a hostname.
For the sake of completeness, here is another function that can be used to convert the number form back into the standard string form
CREATE FUNCTION dbo.IPAddressFromNumber (#IPNumber AS bigint)
RETURNS varchar(15)
BEGIN
RETURN
CONVERT (varchar(15),
CONVERT(varchar(3), CONVERT(int, SUBSTRING(CONVERT(varbinary(4), #IPNumber), 1,1))) + '.' +
CONVERT(varchar(3), CONVERT(int, SUBSTRING(CONVERT(varbinary(4), #IPNumber), 2,1))) + '.' +
CONVERT(varchar(3), CONVERT(int, SUBSTRING(CONVERT(varbinary(4), #IPNumber), 3,1))) + '.' +
CONVERT(varchar(3), CONVERT(int, SUBSTRING(CONVERT(varbinary(4), #IPNumber), 4,1))) )
END
select *
from ip a
join ip_details b
on a.ip_address >= b.ip_start
and a.ip_address <= b.ip_end;
In this, table "a" contains list of IP address and table "b" contains the IP ranges.
Instead of converting the ip address to numeric we can directly compare the string, it will do a byte by byte comparison.
This is working for me(PostgreSQL).
I was thinking along the lines of Gordon's answer, then realized you don't actually need to mess with numbers. If you zero-pad each part of the address, a string comparison works:
DECLARE #search varchar(50) = '192.168.2.50';
WITH DATA AS (
SELECT * FROM ( values
(1, 'Lucas', '192.130.1.1', '192.130.1.254'),
(2, 'Maria', '192.168.2.1', '192.168.2.254'),
(3, 'Julia', '192.150.3.1', '192.150.3.254')
) AS tbl (ID,Name,IPLow,IPHigh)
)
SELECT *
FROM DATA
WHERE REPLACE(STR(PARSENAME( #search, 4 ), 3, 0), ' ', '0')
+ REPLACE(STR(PARSENAME( #search, 3 ), 3, 0), ' ', '0')
+ REPLACE(STR(PARSENAME( #search, 2 ), 3, 0), ' ', '0')
+ REPLACE(STR(PARSENAME( #search, 1 ), 3, 0), ' ', '0')
BETWEEN
REPLACE(STR(PARSENAME( IPLow, 4 ), 3, 0), ' ', '0')
+ REPLACE(STR(PARSENAME( IPLow, 3 ), 3, 0), ' ', '0')
+ REPLACE(STR(PARSENAME( IPLow, 2 ), 3, 0), ' ', '0')
+ REPLACE(STR(PARSENAME( IPLow, 1 ), 3, 0), ' ', '0')
AND
REPLACE(STR(PARSENAME( IPHigh, 4 ), 3, 0), ' ', '0')
+ REPLACE(STR(PARSENAME( IPHigh, 3 ), 3, 0), ' ', '0')
+ REPLACE(STR(PARSENAME( IPHigh, 2 ), 3, 0), ' ', '0')
+ REPLACE(STR(PARSENAME( IPHigh, 1 ), 3, 0), ' ', '0')
You can, of course, put this inside a UDF for simplicity, though watch out for the performance hit on large queries.
CREATE FUNCTION dbo.IP_Comparable(#IP varchar(50))
RETURNS varchar(50)
WITH SCHEMABINDING
BEGIN
RETURN REPLACE(STR(PARSENAME( #IP, 4 ), 3, 0), ' ', '0')
+ REPLACE(STR(PARSENAME( #IP, 3 ), 3, 0), ' ', '0')
+ REPLACE(STR(PARSENAME( #IP, 2 ), 3, 0), ' ', '0')
+ REPLACE(STR(PARSENAME( #IP, 1 ), 3, 0), ' ', '0')
END
GO
DECLARE #search varchar(50) = '192.168.2.50';
WITH DATA AS (
SELECT * FROM ( values
(1, 'Lucas', '192.130.1.1', '192.130.1.254'),
(2, 'Maria', '192.168.2.1', '192.168.2.254'),
(3, 'Julia', '192.150.3.1', '192.150.3.254')
) AS tbl (ID,Name,IPLow,IPHigh)
)
SELECT *
FROM DATA
WHERE dbo.IP_Comparable(#search) BETWEEN dbo.IP_Comparable(IPLow) AND dbo.IP_Comparable(IPHigh)
This will avoid the issue you're having with integer overflows.
Depends on which record you are looking for the high or the low.
select * from table where IPlow like '192.168.2.50' or IPHigh like '192.168.2.50'
have something kinda weird here. I have a database that's called FLDOC. In it has a column called SENTENCE that contains 7 numbers that represent a length of time.
example:
0050000
0750000
0000600
0040615
0000110
In those 7 digits is a length of type since the digits represent YYYMMDD
So what I'd like is a script that can convert it to something like this:
5Y 00M 00D
75Y 00M 00D
6M (or 000Y 6M 00D is fine as well)
4Y 6M 15D etc etc
thanks in advance...
CONCAT is new to SQL Server 2012. If you have previous version of SQL Server, you could do something like this instead to achieve your desired output:
SELECT sentence
,(
CASE
WHEN cast(left(sentence, 3) AS INT) > 0
THEN cast(cast(left(sentence, 3) AS INT) AS VARCHAR(3)) + 'Y '
ELSE cast(left(sentence, 3) AS VARCHAR(3)) + 'Y '
END +
CASE
WHEN cast(substring(sentence, 4, 2) AS INT) > 0
THEN cast(cast(substring(sentence, 4, 2) AS INT) AS VARCHAR(2)) + 'M '
ELSE cast(substring(sentence, 4, 2) AS VARCHAR(2)) + 'M '
END +
CASE
WHEN cast(right(sentence, 2) AS INT) > 0
THEN cast(cast(right(sentence, 2) AS INT) AS VARCHAR(3)) + 'D'
ELSE cast(right(sentence, 2) AS VARCHAR(3)) + 'D'
END
) AS new_sentence
FROM FLDOC;
SQL Fiddle Demo
UPDATE
To answer your question below in the comments, you could maybe just write a update statement like this:
update FLDOC
set sentence = (
CASE
WHEN cast(left(sentence, 3) AS INT) > 0
THEN cast(cast(left(sentence, 3) AS INT) AS VARCHAR(3)) + 'Y '
ELSE cast(left(sentence, 3) AS VARCHAR(3)) + 'Y '
END +
CASE
WHEN cast(substring(sentence, 4, 2) AS INT) > 0
THEN cast(cast(substring(sentence, 4, 2) AS INT) AS VARCHAR(2)) + 'M '
ELSE cast(substring(sentence, 4, 2) AS VARCHAR(2)) + 'M '
END +
CASE
WHEN cast(right(sentence, 2) AS INT) > 0
THEN cast(cast(right(sentence, 2) AS INT) AS VARCHAR(3)) + 'D'
ELSE cast(right(sentence, 2) AS VARCHAR(3)) + 'D'
END
)
Try this query
select convert(varchar(10),left(example,3))+'Y '+
convert(varchar(10),Substring(example,4,3))+'M '+
convert(varchar(10),Right(example,3))+'D'+ from tablename
You can do this with Concat as well:
Select Concat
(
Left(SENTENCE, 3), 'Y ',
SubString(SENTENCE, 4, 2), 'M ',
Right(SENTENCE, 2), 'D'
)
From Table
To condense the expression as in your example, this can be used as well:
Select Concat
(
Case When (IsNumeric(Left(SENTENCE, 3)) = 1 And Left(SENTENCE, 3) <> '000')
Then Convert(Varchar (3), Convert(Int, Left(SENTENCE, 3))) + 'Y ' End,
Case When (IsNumeric(SubString(SENTENCE, 4, 2)) = 1 And SubString(SENTENCE, 4, 2) <> '00')
Then Convert(Varchar (2), Convert(Int, SubString(SENTENCE, 4, 2))) + 'M ' End,
Case When (IsNumeric(Right(SENTENCE, 2)) = 1 And Right(SENTENCE, 2) <> '00')
Then Convert(Varchar (2), Convert(Int, Right(SENTENCE, 2))) + 'D' End
)
From Table