SQL Server 2008 IsNumeric returns 1 - sql

I am trying to do a query using ISNUMERIC but one of the my data record return it as a numeric.
Is there any way that the query return 0 on this data without removing character function?
Declare #Temp Table(Data VarChar(18))
Insert Into #Temp Values('750419.')
Insert Into #Temp Values('7.4')
Select Data,
IsNumeric(Data) As [IsNumeric],
From #Temp
and also I've found a function named but still wont return it to 0
CREATE Function [dbo].[IsInteger](#Value VarChar(18))
Returns Bit
As
Begin
Return IsNull(
(Select Case When CharIndex('.', #Value) >= 0
Then Case When Convert(int, ParseName(#Value, 1)) <> 0
Then 0
Else 1
End
Else 1
End
Where IsNumeric(#Value + 'e0') = 1), 0)
End

Try this :
Declare #Temp Table(Data VarChar(18))
Insert Into #Temp Values('750419.')
Insert Into #Temp Values('7.4')
Select Data,
CASE
WHEN ISNUMERIC(Data) = 0 THEN 0
WHEN Data LIKE '%[^-+ 0-9.]%' THEN 0
WHEN CAST(Data AS NUMERIC(38, 0))=cast(Data AS NUMERIC(38, 10)) then 1
ELSE 0
END
[IsNumeric]
From #Temp

Related

Formatting dates in SQL Server

I want to ask how to format a date in the select statement. For example, I have a date '2000-07-31'. I want the output to be similar to 'Monday, the Thirty-First of July, 2000'
This question has already answer here.
So no built-in method exists for such a conversion.
But if you break the problem into smaller parts, you can use stackoverflow very well to solve the problem.
Check this answer.
I have modified the UDF from that answer to work for ordinal numbers as well, I did not bother with big numbers greater than one million:
CREATE FUNCTION [dbo].[fnNumberToWords] (#Number AS bigint, #ordinals AS bit)
RETURNS varchar(1024)
AS
BEGIN
DECLARE #Below20 TABLE (
ID int IDENTITY (0, 1),
Word varchar(32)
)
DECLARE #Below100 TABLE (
ID int IDENTITY (2, 1),
Word varchar(32)
)
DECLARE #Below100ordinals TABLE (
ID int IDENTITY (2, 1),
Word varchar(32)
)
IF (#ordinals = 0)
BEGIN
INSERT #Below20 (Word)
VALUES ('Zero'), ('One'), ('Two'), ('Three'),
('Four'), ('Five'), ('Six'), ('Seven'),
('Eight'), ('Nine'), ('Ten'), ('Eleven'),
('Twelve'), ('Thirteen'), ('Fourteen'),
('Fifteen'), ('Sixteen'), ('Seventeen'),
('Eighteen'), ('Nineteen')
END
ELSE
BEGIN
INSERT #Below20 (Word)
VALUES ('Zeroth'), ('First'), ('Second'), ('Third'),
('Fourth'), ('Fifth'), ('Sixth'), ('Seventh'),
('Eight'), ('Nineth'), ('Tenth'), ('Eleventh'),
('Twelveth'), ('Thirteenth'), ('Fourteenth'),
('Fifteenth'), ('Sixteenth'), ('Seventeenth'),
('Eighteenth'), ('Nineteenth')
INSERT #Below100ordinals
VALUES ('Twentieth'), ('Thirtieth'), ('Fortieth'), ('Fiftieth'),
('Sixtieth'), ('Seventieth'), ('Eightieth'), ('Ninetieth')
END
INSERT #Below100
VALUES ('Twenty'), ('Thirty'), ('Forty'), ('Fifty'),
('Sixty'), ('Seventy'), ('Eighty'), ('Ninety')
DECLARE #English varchar(1024) = (SELECT
CASE
WHEN #Number = 0 THEN ''
WHEN #Number BETWEEN 1 AND 19 THEN (SELECT
Word
FROM #Below20
WHERE ID = #Number)
WHEN #Number BETWEEN 20 AND 99 THEN CASE
WHEN #ordinals = 1 THEN CASE
WHEN (#Number % 10 > 0) THEN (SELECT
Word
FROM #Below100
WHERE ID = #Number / 10)
+ '-' + dbo.fnNumberToWords(#Number % 10, 1)
ELSE (SELECT
Word
FROM #Below100ordinals
WHERE ID = #Number / 10)
END
ELSE (SELECT
Word
FROM #Below100
WHERE ID = #Number / 10)
+ '-' + dbo.fnNumberToWords(#Number % 10, 0)
END
WHEN #Number BETWEEN 100 AND 999 THEN (dbo.fnNumberToWords(#Number / 100, 0)) + ' Hundred' + CASE
WHEN #ordinals = 1 THEN CASE
WHEN (#Number % 100 > 0) THEN ' ' + dbo.fnNumberToWords(#Number % 100, 1)
ELSE 'th'
END
ELSE ' ' + dbo.fnNumberToWords(#Number % 100, 0)
END
WHEN #Number BETWEEN 1000 AND 999999 THEN (dbo.fnNumberToWords(#Number / 1000, 0)) + ' Thousand' + CASE
WHEN #ordinals = 1 THEN CASE
WHEN (#Number % 1000 > 0) THEN ' ' + dbo.fnNumberToWords(#Number % 1000, 1)
ELSE 'th'
END
ELSE ' ' + dbo.fnNumberToWords(#Number % 1000, 0)
END
ELSE ' INVALID INPUT'
END)
SELECT
#English = RTRIM(#English)
SELECT
#English = RTRIM(LEFT(#English, LEN(#English) - 1))
WHERE RIGHT(#English, 1) = '-'
RETURN (#English)
END
With this function you can write
DECLARE #d date = '20000731'
SELECT datename(WEEKDAY, datepart(day,#d))+
', the '+ [dbo].[fnNumberToWords](DAY(#d),1) +
' of ' + datename(MONTH ,#d) +
', year '+ [dbo].[fnNumberToWords](YEAR(#d),0)
To get result like this:
Thursday, the Thirty-First of July, year Two Thousand
It would be probably much more difficult for computer non-friendly languages other than English.
Create UDF using this script or even try to improve it.
declare #t table(col1 int,col2 varchar(50),col3 int)
insert into #t (col1,col2) VALUES (0,'Zero'),(1,'First'),(2,'Second')
,(3,'Third'),(4,'Fourth'),(5,'fifth'),(6,'Sixth'),(7,'Seventh'),(8,'Eighth')
,(9,'Ninth'),(10,'Tenth'),(11,'eleventh'),(12,'Twelveth'),(13,'thirteenth')
,(14,'Fourteenth'),(15,'Fifteeth'),(16,'Sixteenth'),(17,'Seventeenth')
,(18,'Eighteenth'),(19,'Nineteenth'),(20,'Twenty'),(30,'Thirty')
declare #input varchar(10)='21'
declare #Words varchar(2000)=''
declare #i int=len(#input)
while((len(#input)>0))
begin
if(#input>=0 and #input<=19 and #i=len(#input))
begin
select #Words=#Words+' '+ col2 from #t where col1 =#input
BREAK
END
else if(len(#input) between 3 and 4)
BEGIN
select #Words=#Words+' '+ col2 from #t where col1 =#input/cast(('1'+replicate('0',len(#input)-1)) as int)
select #Words=#Words+' '+ col2 from #t where col1 ='1'+replicate('0',len(#input)-1)
END
else
begin
select #Words=#Words+' '+ col2 from #t where col1 =left(#input,1)+ replicate('0',#i-1)
END
set #input=stuff(#input,1,1,'')
if(cast(#input as int)=0)
BREAK
set #i=#i-1
end
select #Words
then do this
declare #Input date='2017-04-30'
select datename(WEEKDAY, datepart(day,#input))+' '+'the '
+fn.colname
+' '+'of '+datename(MONTH, #Input)+' 'cast(datepart(year,#input) as varchar)
cross apply(select colname from fn_NumtoWords(datepart(day,#input)))fn
Try this:
select Datename(Weekday,Month('2000-07-31')), Cast(Day('2000-07-31') As char), YEAR('2000-07-31')

Convert unknown number of comma separated varchars within 1 column into multiple columns

Let me say upfront that I'm a brand-spanking-new SQL Developer. I've researched this and haven't been able to find the answer.
I'm working in SSMS 2012 and I have a one-column table (axis1) with values like this:
axis1
296.90, 309.4
296.32, 309.81
296.90
300.11, 309.81, 311, 313.89, 314.00, 314.01, V61.8, V62.3
I need to convert this column into multiple columns like so:
axis1 axis2 axis3 axis4
296.90 309.4 null null
296.32 309.81 null null
296.90 null null null
300.11 309.81 311 313.89...
So far I've tried/considered:
select case when charindex(',',Axis1,1)>0
then substring(Axis1,1,CHARINDEX(',',Axis1,1)-1)
else Axis1
end as Axis1
from tablex
That works fine for a known number of column values, but there could be 0, 1, or 20+ values in this column.
Is there any way to split an unknown quantity of comma-separated values that are in one column into multiple single-value columns?
Thanks in advance for any help everyone!
I made one assumption while creating this answer, which is that you need this as a separate stored proc.
Step 1
Create a data type to enable the use of passing a table-valued parameter (TVP) into a stored proc.
use db_name
GO
create type axisTable as table
(
axis1 varchar(max)
)
GO
Step 2
Create the procedure to parse out the values.
USE [db_name]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[usp_util_parse_out_axis]
(
#axis_tbl_prelim axisTable readonly
)
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
declare #axis_tbl axisTable
--since TVP's are readonly, moving the data in the TVP to a local variable
--so that the update statement later on will work as expected
insert into #axis_tbl
select *
from #axis_tbl_prelim
declare #comma_cnt int
, #i int
, #sql_dyn nvarchar(max)
, #col_list nvarchar(max)
--dropping the global temp table if it already exists
if object_id('tempdb..##axis_unpvt') is not null
drop table ##axis_unpvt
create table ##axis_unpvt
(
axis_nbr varchar(25)
, row_num int
, axis_val varchar(max)
)
--getting the most commas
set #comma_cnt = (select max(len(a.axis1) - len(replace(a.axis1, ',', '')))
from #axis_tbl as a)
set #i = 1
while #i <= #comma_cnt + 1
begin --while loop
--insert the data into the "unpivot" table one parsed value at a time (all rows)
insert into ##axis_unpvt
select 'axis' + cast(#i as varchar(3))
, row_number() over (order by (select 100)) as row_num --making sure the data stays in the right row
, case when charindex(',', a.axis1, 0) = 0 and len(a.axis1) = 0 then NULL
when charindex(',', a.axis1, 0) = 0 and len(a.axis1) > 0 then a.axis1
when charindex(',', a.axis1, 0) > 0 then replace(left(a.axis1, charindex(',', a.axis1, 0)), ',', '')
else NULL
end as axis1
from #axis_tbl as a
--getting rid of the value that was just inserted from the source table
update a
set a.axis1 = case when charindex(',', a.axis1, 0) = 0 and len(a.axis1) > 0 then NULL
when charindex(',', a.axis1, 0) > 0 then rtrim(ltrim(right(a.axis1, (len(a.axis1) - charindex(',', a.axis1, 0)))))
else NULL
end
from #axis_tbl as a
where 1=1
and (charindex(',', a.axis1, 0) = 0 and len(a.axis1) > 0
or charindex(',', a.axis1, 0) > 0)
--incrementing toward terminating condition
set #i += 1
end --while loop
--getting list of what the columns will be after pivoting
set #col_list = (select stuff((select distinct ', ' + axis_nbr
from ##axis_unpvt as a
for xml path ('')),1,1,''))
--building the pivot statement
set #sql_dyn = '
select '
+ #col_list +
'
from ##axis_unpvt as a
pivot (max(a.axis_val)
for a.axis_nbr in ('
+ #col_list +
')) as p'
--executing the pivot statement
exec(#sql_dyn);
END
Step 3
Make a procedure call using the data type created in Step 1 as the parameter.
use db_name
go
declare #tvp as axisTable
insert into #tvp values ('296.90, 309.4')
insert into #tvp values ('296.32, 309.81')
insert into #tvp values ('296.90')
insert into #tvp values ('300.11, 309.81, 311, 313.89, 314.00, 314.01, V61.8, V62.3')
exec db_name.dbo.usp_util_parse_out_axis #tvp
Results from your example are as follows:

Incrementing Character value in T-sql

I have 2 set of values in a column i.e first 4 character are characters and next 4 character are numeric.
Ex:AAAA1234
Now I have to increment the value from right end i.e when numeric value reached 9999 then I have to increment character by 1 character.
Sample :
Consider the last value stored in a column is AAAA9999 then next incremented values should be in a sequence AAAB9999,....... AABZ9999,..... BZZZ9999..... ZZZZ9999(last value). And when it reaches ZZZZ9999 then I have to reset the value to AAAA0001.
How can do it in T-SQL ???
Here is a conceptual script, which does what you want. You will need to tweak it to suit your requirements
DECLARE #test table(TestValue char(8))
DECLARE #CharPart char(4),#NumPart int
SET #CharPart = 'AAAA'
SET #NumPart = 1
WHILE #NumPart <=9999
BEGIN
INSERT INTO #test
SELECT #CharPart+RIGHT(('0000'+CAST(#NumPart AS varchar(4))),4)
IF #NumPart = 9999
BEGIN
IF SUBSTRING(#CharPart,4,1)<>'Z'
BEGIN
SET #CharPart = LEFT(#CharPart,3)+CHAR(ASCII(SUBSTRING(#CharPart,4,1))+1)
SET #NumPart = 1
END
ELSE IF SUBSTRING(#CharPart,4,1)='Z' AND SUBSTRING(#CharPart,3,1) <>'Z'
BEGIN
SET #CharPart = LEFT(#CharPart,2)+CHAR(ASCII(SUBSTRING(#CharPart,3,1))+1)+RIGHT(#CharPart,1)
SET #NumPart = 1
END
ELSE IF SUBSTRING(#CharPart,3,1)='Z' AND SUBSTRING(#CharPart,2,1) <>'Z'
BEGIN
SET #CharPart = LEFT(#CharPart,1)+CHAR(ASCII(SUBSTRING(#CharPart,2,1))+1)+RIGHT(#CharPart,2)
SET #NumPart = 1
END
ELSE IF SUBSTRING(#CharPart,1,1)<>'Z'
BEGIN
SET #CharPart = CHAR(ASCII(SUBSTRING(#CharPart,1,1))+1)+RIGHT(#CharPart,3)
SET #NumPart = 1
END
ELSE IF SUBSTRING(#CharPart,1,1)='Z'
BEGIN
SET #CharPart = 'AAAA'
SET #NumPart = 1
INSERT INTO #test
SELECT #CharPart+RIGHT(('0000'+CAST(#NumPart AS varchar(4))),4)
BREAK
END
END
ELSE
BEGIN
SET #NumPart=#NumPart+1
END
END
SELECT * FROM #test
With the help of PATINDEX,SUBSTRING,ASCII functions you can achieve your special cases.
(I have found the solution for your special cases). Likewise you can add your own addition feature.
create table #temp(col1 varchar(20))
insert into #temp values('AAAA9999')
insert into #temp values('AAAZ9999')
insert into #temp values('AAZZ9999')
insert into #temp values('AZZZ9999')
insert into #temp values('ZZZZ9999')
select * from #temp
select col1,
case when cast(substring(col1,patindex('%[0-9]%',col1),len(col1)) as int) = 9999 and left(col1,4) <> 'ZZZZ'
then
case
when substring(col1,(patindex('%[0-9]%',col1)-1),1) <> 'Z' then left(col1,3)+char(ASCII(substring(col1,(patindex('%[0-9]%',col1)-1),1)) + 1)+right(col1,4)
when substring(col1,(patindex('%[0-9]%',col1)-2),1) <> 'Z' then left(col1,2)+char(ASCII(substring(col1,(patindex('%[0-9]%',col1)-2),1)) + 1)+right(col1,5)
when substring(col1,(patindex('%[0-9]%',col1)-3),1) <> 'Z' then left(col1,1)+char(ASCII(substring(col1,(patindex('%[0-9]%',col1)-3),1)) + 1)+right(col1,6)
when substring(col1,(patindex('%[0-9]%',col1)-4),1) <> 'Z' then char(ASCII(substring(col1,(patindex('%[0-9]%',col1)-4),1)) + 1)+right(col1,7)
end
else 'AAAA0001'
end as outputofcol1
--patindex('%[0-9]%',col1)-1 as charpos,
--substring(col1,(patindex('%[0-9]%',col1)-1),1) as substr4,
--substring(col1,(patindex('%[0-9]%',col1)-2),1) as substr3,
--substring(col1,(patindex('%[0-9]%',col1)-3),1) as substr2,
--substring(col1,(patindex('%[0-9]%',col1)-4),1) as substr1
--ASCII(substring(col1,(patindex('%[0-9]%',col1)-1),1)) as ASC_value
from #temp
The following function should return the desired value:
IF OBJECT_ID (N'dbo.ufnGetIndexValue') IS NOT NULL
DROP FUNCTION dbo.ufnGetIndexValue;
GO
CREATE FUNCTION dbo.ufnGetIndexValue(#MainString CHAR(8))
RETURNS CHAR(8)
AS
BEGIN
DECLARE #NumberPart INT
DECLARE #StringPart CHAR(4)
DECLARE #Position TINYINT
DECLARE #char CHAR
SET #NumberPart=CONVERT(INT,SUBSTRING(#MainString,5,8))
SET #StringPart=SUBSTRING(#MainString,1,4)
IF #NumberPart=9999
BEGIN
SET #NumberPart=1111;
SET #Position=4
WHILE #Position >= 1
BEGIN
SET #char=SUBSTRING(#StringPart,#Position,1)
IF(#char!='Z')
BEGIN
SET #char=CHAR(ASCII(#char)+1);
SET #StringPart = STUFF(#StringPart,#Position,1,#char);
BREAK;
END
SET #StringPart = STUFF(#StringPart,#Position,1,'A');
SET #Position-=1;
END
END
ELSE
BEGIN
SET #NumberPart+=1;
END
SET #MainString=#StringPart+CAST(#NumberPart AS CHAR(4));
RETURN #MainString
END
GO
Here is a scalar select function that do the increment.
CREATE FUNCTION dbo.inc_serial( #id char(8) )
RETURNS char(8) BEGIN
select #id = case when SUBSTRING(id,2,1) <> '[' then id else STUFF( id, 1, 2, char(((ascii(id)+1-65)%26)+65) + 'A' ) end from (
select case when SUBSTRING(id,3,1) <> '[' then id else STUFF( id, 2, 2, char(ascii(right(id,7))+1) + 'A' ) end as id from (
select case when SUBSTRING(id,4,1) <> '[' then id else STUFF( id, 3, 2, char(ascii(right(id,6))+1) + 'A' ) end as id from (
select
case when right(#id,4) < '9999'
then concat( left(#id,4), right(concat( '000', (cast(right(#id,4) as smallint)+1) ), 4 ) )
else concat( left(#id,3), char(ascii(right(#id,5))+1), '0001' ) end as id
) t1 ) t2 ) t3
RETURN #id
END
Basically, the code just add one to the number, and repeatingly carring overflow up to the left.
If your table always has one and only one row to be updated (e.g. an option/flag table):
UPDATE [table] SET [serial] = dbo.inc_serial( [serial] );
If your table has multiple rows, you will need an identity or high precision creation time column, so that we know where to continue from after reset.
INSERT INTO [table] (serial) VALUES ( dbo.inc_serial((
select top 1 case when count(*) > 0 then max([serial]) else 'AAAA0000' end AS id
from [table] where [id] = ( select max([id]) from [table] )
)));
For concurrency safety, use XLOCK,ROWLOCK,HOLDLOCK to lock the table.
They are obmitted from the examples for simplicity.
If you do not like udf, you can embedded the query inline.
An inline example for first case:
UPDATE [table] SET [serial] = ((
select case when SUBSTRING(id,2,1) <> '[' then id else STUFF( id, 1, 2, char(((ascii(id)+1-65)%26)+65) + 'A' ) end as id from (
select case when SUBSTRING(id,3,1) <> '[' then id else STUFF( id, 2, 2, char(ascii(right(id,7))+1) + 'A' ) end as id from (
select case when SUBSTRING(id,4,1) <> '[' then id else STUFF( id, 3, 2, char(ascii(right(id,6))+1) + 'A' ) end as id from (
select
case when right(id,4) < '9999'
then concat( left(id,4), right(concat( '000', (cast(right(id,4) as smallint)+1) ), 4 ) )
else concat( left(id,3), char(ascii(right(id,5))+1), '0001' ) end as id
from (
select top 1 [serial] as id from [table] with (XLOCK,ROWLOCK,HOLDLOCK)
) t0
) t1 ) t2 ) t3
))
The function can also be written as an inline table value function for better performance, at cost of more complex usage, but I would not border unless it frequently runs on multiple rows.

How to compare software versions using SQL Server?

When trying to compare software versions 5.12 to 5.8, version 5.12 is newer, however mathematically 5.12 is less than 5.8. How would I compare the two versions so that a newer version returns 'Y'?
SELECT CASE WHEN 5.12 > 5.8 THEN 'Y' ELSE 'N' END
Possible Solutions
Add a 0 after the decimal in 5.8 so that it compares 5.08 to 5.12, however it seems like this would require a bit of code.
Simply compare values after the decimal (ie. 12 > 8), however this fails when the version rolls to 6.0.
Use reverse logic and assume that if 5.12 is less than 5.8 to return 'Y'. I believe this would fail when the version rolls to 6.0.
You could use hierarchyid
Which you can use by putting a / at the end and start of the string and casting it
e.g.
SELECT CASE WHEN cast('/5.12/' as hierarchyid) > cast('/5.8/' as hierarchyid) THEN 'Y' ELSE 'N' END
That returns a Y
declare #v1 varchar(100) = '5.12'
declare #v2 varchar(100) = '5.8'
select
case
when CONVERT(int, LEFT(#v1, CHARINDEX('.', #v1)-1)) < CONVERT(int, LEFT(#v2, CHARINDEX('.', #v2)-1)) then 'v2 is newer'
when CONVERT(int, LEFT(#v1, CHARINDEX('.', #v1)-1)) > CONVERT(int, LEFT(#v2, CHARINDEX('.', #v2)-1)) then 'v1 is newer'
when CONVERT(int, substring(#v1, CHARINDEX('.', #v1)+1, LEN(#v1))) < CONVERT(int, substring(#v2, CHARINDEX('.', #v2)+1, LEN(#v1))) then 'v2 is newer'
when CONVERT(int, substring(#v1, CHARINDEX('.', #v1)+1, LEN(#v1))) > CONVERT(int, substring(#v2, CHARINDEX('.', #v2)+1, LEN(#v1))) then 'v1 is newer'
else 'same!'
end
There was a very good solution from a duplicate question here:
How to compare SQL strings that hold version numbers like .NET System.Version class?
After playing with the query for a while, I learned that it was not able to compare the last part when there are 4 or more parts (say, if the version number was 1.2.3.4, it would always treat the last one as 0). I have fixed that issue as well as came up with another function to compare two version numbers.
CREATE Function [dbo].[VersionNthPart](#version as nvarchar(max), #part as int) returns int as
Begin
Declare
#ret as int = null,
#start as int = 1,
#end as int = 0,
#partsFound as int = 0,
#terminate as bit = 0
if #version is not null
Begin
Set #ret = 0
while #partsFound < #part
Begin
Set #end = charindex('.', #version, #start)
If #end = 0 -- did not find the dot. Either it was last part or the part was missing.
begin
if #part - #partsFound > 1 -- also this isn't the last part so it must bail early.
begin
set #terminate = 1
end
Set #partsFound = #part
SET #end = len(#version) + 1; -- get the full length so that it can grab the whole of the final part.
end
else
begin
SET #partsFound = #partsFound + 1
end
If #partsFound = #part and #terminate = 0
begin
Set #ret = Convert(int, substring(#version, #start, #end - #start))
end
Else
begin
Set #start = #end + 1
end
End
End
return #ret
End
GO
CREATE FUNCTION [dbo].[CompareVersionNumbers]
(
#Source nvarchar(max),
#Target nvarchar(max),
#Parts int = 4
)
RETURNS INT
AS
BEGIN
/*
-1 : target has higher version number (later version)
0 : same
1 : source has higher version number (later version)
*/
DECLARE #ReturnValue as int = 0;
DECLARE #PartIndex as int = 1;
DECLARE #SourcePartValue as int = 0;
DECLARE #TargetPartValue as int = 0;
WHILE (#PartIndex <= #Parts AND #ReturnValue = 0)
BEGIN
SET #SourcePartValue = [dbo].[VersionNthPart](#Source, #PartIndex);
SET #TargetPartValue = [dbo].[VersionNthPart](#Target, #PartIndex);
IF #SourcePartValue > #TargetPartValue
SET #ReturnValue = 1
ELSE IF #SourcePartValue < #TargetPartValue
SET #ReturnValue = -1
SET #PartIndex = #PartIndex + 1;
END
RETURN #ReturnValue
END
Usage/Test case:
declare #Source as nvarchar(100) = '4.9.21.018'
declare #Target as nvarchar(100) = '4.9.21.180'
SELECT [dbo].[CompareVersionNumbers](#Source, #Target, DEFAULT) -- default version parts are 4
SET #Source = '1.0.4.1'
SET #Target = '1.0.1.8'
SELECT [dbo].[CompareVersionNumbers](#Source, #Target, 4) -- typing out # of version parts also works
SELECT [dbo].[CompareVersionNumbers](#Source, #Target, 2) -- comparing only 2 parts should be the same
SET #Target = '1.0.4.1.5'
SELECT [dbo].[CompareVersionNumbers](#Source, #Target, 4) -- only comparing up to parts 4 so they are the same
SELECT [dbo].[CompareVersionNumbers](#Source, #Target, 5) -- now comparing 5th part which should indicate that the target has higher version number
I recommend to create a SQL CLR function:
public partial class UserDefinedFunctions
{
[SqlFunction(Name = "CompareVersion")]
public static bool CompareVersion(SqlString x, SqlString y)
{
return Version.Parse(x) > Version.Parse(y);
}
}
Notes:
SqlString has explicit cast to string.
Pass full version string as of a.b.c.d
I encountered this when trying to filter SQL rows based on semantic versioning. My solution was a bit different, in that I wanted to store configuration rows tagged with a semantic version number and then select rows compatible with a running version of our software.
Assumptions:
My software will include a configuration setting containing the current version number
Data-driven configuration rows will include a min version number
I need to be able to select configuration rows where min <= current.
Examples:
Version 1.0.0 should include: 1.0.0, 1.0.0-*, 1.0.0-beta.1
Version 1.0.0 should exclude: 1.0.1, 1.1.0, 2.0.0
Version 1.1.0-beta.2 should include: 1.0.0, 1.0.1, 1.1.0-beta.1, 1.1.0-beta.2
Version 1.1.0-beta.2 should exclude: 1.1.0, 1.1.1, 1.2.0, 2.0.0, 1.1.1-beta.1
The MSSQL UDF is:
CREATE FUNCTION [dbo].[SemanticVersion] (
#Version nvarchar(50)
)
RETURNS nvarchar(255)
AS
BEGIN
DECLARE #hyphen int = CHARINDEX('-', #version)
SET #Version = REPLACE(#Version, '*', ' ')
DECLARE
#left nvarchar(50) = CASE #hyphen WHEN 0 THEN #version ELSE SUBSTRING(#version, 1, #hyphen-1) END,
#right nvarchar(50) = CASE #hyphen WHEN 0 THEN NULL ELSE SUBSTRING(#version, #hyphen+1, 50) END,
#normalized nvarchar(255) = '',
#buffer int = 8
WHILE CHARINDEX('.', #left) > 0 BEGIN
SET #normalized = #normalized + CASE ISNUMERIC(LEFT(#left, CHARINDEX('.', #left)-1))
WHEN 0 THEN LEFT(#left, CHARINDEX('.', #left)-1)
WHEN 1 THEN REPLACE(STR(LEFT(#left, CHARINDEX('.', #left)-1), #buffer), SPACE(1), '0')
END + '.'
SET #left = SUBSTRING(#left, CHARINDEX('.', #left)+1, 50)
END
SET #normalized = #normalized + CASE ISNUMERIC(#left)
WHEN 0 THEN #left
WHEN 1 THEN REPLACE(STR(#left, #buffer), SPACE(1), '0')
END
SET #normalized = #normalized + '-'
IF (#right IS NOT NULL) BEGIN
WHILE CHARINDEX('.', #right) > 0 BEGIN
SET #normalized = #normalized + CASE ISNUMERIC(LEFT(#right, CHARINDEX('.', #right)-1))
WHEN 0 THEN LEFT(#right, CHARINDEX('.', #right)-1)
WHEN 1 THEN REPLACE(STR(LEFT(#right, CHARINDEX('.', #right)-1), #buffer), SPACE(1), '0')
END + '.'
SET #right = SUBSTRING(#right, CHARINDEX('.', #right)+1, 50)
END
SET #normalized = #normalized + CASE ISNUMERIC(#right)
WHEN 0 THEN #right
WHEN 1 THEN REPLACE(STR(#right, #buffer), SPACE(1), '0')
END
END ELSE
SET #normalized = #normalized + 'zzzzzzzzzz'
RETURN #normalized
END
SQL tests include:
SELECT CASE WHEN dbo.SemanticVersion('1.0.0-alpha') < dbo.SemanticVersion('1.0.0-alpha.1') THEN 'Success' ELSE 'Failure' END
SELECT CASE WHEN dbo.SemanticVersion('1.0.0-alpha.1') < dbo.SemanticVersion('1.0.0-alpha.beta') THEN 'Success' ELSE 'Failure' END
SELECT CASE WHEN dbo.SemanticVersion('1.0.0-alpha.beta') < dbo.SemanticVersion('1.0.0-beta') THEN 'Success' ELSE 'Failure' END
SELECT CASE WHEN dbo.SemanticVersion('1.0.0-beta') < dbo.SemanticVersion('1.0.0-beta.2') THEN 'Success' ELSE 'Failure' END
SELECT CASE WHEN dbo.SemanticVersion('1.0.0-beta.2') < dbo.SemanticVersion('1.0.0-beta.11') THEN 'Success' ELSE 'Failure' END
SELECT CASE WHEN dbo.SemanticVersion('1.0.0-beta.11') < dbo.SemanticVersion('1.0.0-rc.1') THEN 'Success' ELSE 'Failure' END
SELECT CASE WHEN dbo.SemanticVersion('1.0.0-rc.1') < dbo.SemanticVersion('1.0.0') THEN 'Success' ELSE 'Failure' END
SELECT CASE WHEN dbo.SemanticVersion('1.0.0-*') <= dbo.SemanticVersion('1.0.0') THEN 'Success' ELSE 'Failure' END
SELECT CASE WHEN dbo.SemanticVersion('1.0.*') <= dbo.SemanticVersion('1.0.0') THEN 'Success' ELSE 'Failure' END
SELECT CASE WHEN dbo.SemanticVersion('1.*') <= dbo.SemanticVersion('1.0.0') THEN 'Success' ELSE 'Failure' END
SELECT CASE WHEN dbo.SemanticVersion('*') <= dbo.SemanticVersion('1.0.0') THEN 'Success' ELSE 'Failure' END
SELECT CASE WHEN dbo.SemanticVersion('1.0.0-*') <= dbo.SemanticVersion('1.0.0') THEN 'Success' ELSE 'Failure' END
SELECT CASE WHEN dbo.SemanticVersion('1.0.1-*') > dbo.SemanticVersion('1.0.0') THEN 'Success' ELSE 'Failure' END
SELECT CASE WHEN dbo.SemanticVersion('1.0.1-*') <= dbo.SemanticVersion('1.0.1') THEN 'Success' ELSE 'Failure' END
SELECT CASE WHEN dbo.SemanticVersion('1.1.*') > dbo.SemanticVersion('1.0.9') THEN 'Success' ELSE 'Failure' END
SELECT CASE WHEN dbo.SemanticVersion('1.1.*') <= dbo.SemanticVersion('1.2.0') THEN 'Success' ELSE 'Failure' END
SELECT CASE WHEN dbo.SemanticVersion('1.*') <= dbo.SemanticVersion('2.0.0') THEN 'Success' ELSE 'Failure' END
SELECT CASE WHEN dbo.SemanticVersion('1.*') > dbo.SemanticVersion('0.9.9-beta-219') THEN 'Success' ELSE 'Failure' END
SELECT CASE WHEN dbo.SemanticVersion('*') <= dbo.SemanticVersion('0.0.1-alpha-1') THEN 'Success' ELSE 'Failure' END
Two steps, first compare the left of the decimal point and after that compare the right.
Possible solution:
declare #v1 varchar(100) = '5.12'
declare #v2 varchar(100) = '5.8'
select case
when CONVERT(int, LEFT(#v1, CHARINDEX('.', #v1)-1)) < CONVERT(int, LEFT(#v2, CHARINDEX('.', #v2)-1)) then 'v2 is newer'
when CONVERT(int, LEFT(#v1, CHARINDEX('.', #v1)-1)) > CONVERT(int, LEFT(#v2, CHARINDEX('.', #v2)-1)) then 'v1 is newer'
when CONVERT(int, RIGHT(#v1, LEN(#v1) - CHARINDEX('.', #v1))) < CONVERT(int, RIGHT(#v2, LEN(#v2) - CHARINDEX('.', #v2))) then 'v2 is newer'
when CONVERT(int, RIGHT(#v1, LEN(#v1) - CHARINDEX('.', #v1))) > CONVERT(int, RIGHT(#v2, LEN(#v2) - CHARINDEX('.', #v2))) then 'v1 is newer'
else 'same!' end as 'Version Test'
Do not store in a string what is not a string. Alternative is creating your own data type (in C# - allowed for some time) that stored the versions as a sequence of bytes and implements proper comparison logic.
As suggested by AF you can compare the int part and then the decimal part .Apart from all the answers given there is one more way to do it using parsename .You could try something like this
case when cast(#var as int)>cast(#var2 as int) then 'Y'
when cast(PARSENAME(#var,1) as int) > cast(PARSENAME(#var2,1) as int) THEN 'Y'
Declare #var float
Declare #var2 float
set #var=5.14
set #var2=5.8
Select case when cast(#var as int)>cast(#var2 as int) then 'Y'
when cast(PARSENAME(#var,1) as int)> cast(PARSENAME(#var2,1) as int) THEN 'Y'
else 'N' END
You don't say so in the question, but your comment under Tomtom's answer suggests you are storing the version numbers as [decimals][d]. I guess that you have a table like this:
CREATE TABLE ReleaseHistory (
VersionNumber DECIMAL(6,3) NOT NULL
);
GO
INSERT INTO ReleaseHistory (
VersionNumber
)
VALUES
(5.12),
(5.8),
(12.34),
(3.14),
(0.78),
(1.0);
GO
The following query is an attempt to rank versions by the order in which they would be released:
SELECT
VersionNumber,
RANK() OVER (ORDER BY VersionNumber) AS ReleaseOrder
FROM ReleaseHistory;
It produces the following result set:
VersionNumber ReleaseOrder
--------------------------------------- --------------------
0.780 1
1.000 2
3.140 3
5.120 4
5.800 5
12.340 6
This is not what we expect. Version 5.8 was released before version 5.12!
Split the version number into its major and minor components to rank the version numbers properly. One way to do this is to convert the decimal value to a string and split on the period. The T-SQL syntax for this is ugly (the language is not designed for string processing):
WITH VersionStrings AS (
SELECT CAST(VersionNumber AS VARCHAR(6)) AS VersionString
FROM ReleaseHistory
),
VersionNumberComponents AS (
SELECT
CAST(SUBSTRING(VersionString, 1, CHARINDEX('.', VersionString) - 1) AS INT) AS MajorVersionNumber,
CAST(SUBSTRING(VersionString, CHARINDEX('.', VersionString) + 1, LEN(VersionString) - CHARINDEX('.', VersionString)) AS INT) AS MinorVersionNumber
FROM VersionStrings
)
SELECT
CAST(MajorVersionNumber AS VARCHAR(3)) + '.' + CAST(MinorVersionNumber AS VARCHAR(3)) AS VersionString,
RANK() OVER (ORDER BY MajorVersionNumber, MinorVersionNumber) AS ReleaseOrder
FROM VersionNumberComponents;
But it provides the expected result:
VersionString ReleaseOrder
------------- --------------------
0.780 1
1.0 2
3.140 3
5.120 4
5.800 5
12.340 6
As Tomtom replied, decimal is a not a good type to store a version number. It would be better to store the version number in two positive integer columns, one containing the major version number and the other containing the minor version number.
This is based on SeanW's answer but this solution allows for the following format [major].[minor].[build]. It maybe used for SQL 2K and when cursor is not an option.
declare #v1 varchar(100) = '1.4.020'
declare #v2 varchar(100) = '1.4.003'
declare #v1_dot1_pos smallint /*position - 1st version - 1st dot */
declare #v1_dot2_pos smallint /*position - 1st version - 2nd dot */
declare #v2_dot1_pos smallint /*position - 2nd version - 1st dot */
declare #v2_dot2_pos smallint /*position - 2nd version - 2nd dot */
-------------------------------------------------
-- get the pos of the first and second dots
-------------------------------------------------
SELECT
#v1_dot1_pos=CHARINDEX('.', #v1),
#v2_dot1_pos=CHARINDEX('.', #v2),
#v1_dot2_pos=charindex( '.', #v1, charindex( '.', #v1 ) + 1 ),
#v2_dot2_pos=charindex( '.', #v2, charindex( '.', #v2 ) + 1 )
-------------------------------------------------
-- break down the parts
-------------------------------------------------
DECLARE #v1_major int, #v2_major int
DECLARE #v1_minor int, #v2_minor int
DECLARE #v1_build int, #v2_build int
SELECT
#v1_major = CONVERT(int,LEFT(#v1,#v1_dot1_pos-1)),
#v1_minor = CONVERT(int,SUBSTRING(#v1,#v1_dot1_pos+1,(#v1_dot2_pos-#v1_dot1_pos)-1)),
#v1_build = CONVERT(int,RIGHT(#v1,(LEN(#v1)-#v1_dot2_pos))),
#v2_major = CONVERT(int,LEFT(#v2,#v2_dot1_pos-1)),
#v2_minor = CONVERT(int,SUBSTRING(#v2,#v2_dot1_pos+1,(#v2_dot2_pos-#v2_dot1_pos)-1)),
#v2_build = CONVERT(int,RIGHT(#v2,(LEN(#v2)-#v2_dot2_pos)))
-------------------------------------------------
-- return the difference
-------------------------------------------------
SELECT
Case
WHEN #v1_major < #v2_major then 'v2 is newer'
WHEN #v1_major > #v2_major then 'v1 is newer'
WHEN #v1_minor < #v2_minor then 'v2 is newer'
WHEN #v1_minor > #v2_minor then 'v1 is newer'
WHEN #v1_build < #v2_build then 'v2 is newer'
WHEN #v1_build > #v2_build then 'v1 is newer'
ELSE '!Same'
END
The solution that was implemented:
CREATE FUNCTION [dbo].[version_compare]
(
#v1 VARCHAR(5), #v2 VARCHAR(5)
)
RETURNS tinyint
AS
BEGIN
DECLARE #v1_int tinyint, #v1_frc tinyint,
#v2_int tinyint, #v2_frc tinyint,
#ResultVar tinyint
SET #ResultVar = 0
SET #v1_int = CONVERT(tinyint, LEFT(#v1, CHARINDEX('.', #v1) - 1))
SET #v1_frc = CONVERT(tinyint, RIGHT(#v1, LEN(#v1) - CHARINDEX('.', #v1)))
SET #v2_int = CONVERT(tinyint, LEFT(#v2, CHARINDEX('.', #v2) - 1))
SET #v2_frc = CONVERT(tinyint, RIGHT(#v2, LEN(#v2) - CHARINDEX('.', #v2)))
SELECT #ResultVar = CASE
WHEN #v2_int > #v1_int THEN 2
WHEN #v1_int > #v2_int THEN 1
WHEN #v2_frc > #v1_frc THEN 2
WHEN #v1_frc > #v2_frc THEN 1
ELSE 0 END
-- Return the result of the function
RETURN #ResultVar
END
GO
This recursive query would convert any '.'-separated version numbers into comparable strings left-padding each element to 10 characters thus allowing to compare versions with or without build number and accommodating for non-numeric characters:
WITH cte (VersionNumber) AS (
SELECT '1.23.456' UNION ALL
SELECT '2.3' UNION ALL
SELECT '0.alpha-3'
),
parsed (VersionNumber, Padded) AS (
SELECT
CAST(SUBSTRING(VersionNumber, CHARINDEX('.', VersionNumber) + 1, LEN(VersionNumber)) + '.' AS NVARCHAR(MAX)),
CAST(RIGHT(REPLICATE('0', 10) + LEFT(VersionNumber, CHARINDEX('.', VersionNumber) - 1), 10) AS NVARCHAR(MAX))
FROM cte
UNION ALL
SELECT
SUBSTRING(VersionNumber, CHARINDEX('.', VersionNumber) + 1, LEN(VersionNumber)),
Padded + RIGHT(REPLICATE('0', 10) + LEFT(VersionNumber, CHARINDEX('.', VersionNumber) - 1), 10)
FROM parsed WHERE CHARINDEX('.', VersionNumber) > 0
)
SELECT Padded
FROM parsed
WHERE VersionNumber = ''
ORDER BY Padded;
Padded
------------------------------
0000000000000alpha-3
000000000100000000230000000456
00000000020000000003
I have created (with inspiration from Eva Lacy (above)), this function:
CREATE or alter function dbo.IsVersionNewerThan
(
#Source nvarchar(max),
#Target nvarchar(max)
)
RETURNS table
as
/*
-1 : target has higher version number (later version)
0 : same
1 : source has higher version number (later version)
test harness:
; WITH tmp
AS
(
SELECT '1.0.0.5' AS Version
UNION ALL SELECT '0.0.0.0'
UNION ALL SELECT '1.5.0.6'
UNION ALL SELECT '2.0.0'
UNION ALL SELECT '2.0.0.0'
UNION ALL SELECT '2.0.1.1'
UNION ALL SELECT '15.15.1323.22'
UNION ALL SELECT '15.15.622.55'
)
SELECT tmp.version, isGreather from tmp
outer apply (select * from dbo.IsVersionNewerThan(tmp.Version, '2.0.0.0')) as IsG
*/
return (
select CASE
when cast('/' + #Source + '/' as hierarchyid) > cast('/' + #Target + '/' as hierarchyid) THEN 1
when #Source = #Target then 0
else -1
end as IsGreather
)
go
The test script is included as a comment.
It works, as long as you do not have versions like '1.5.06.2' (note the zero).
SQL Server thinks this function has is_inlineable = 1, which bodes well for the performance.
Then my SQL code can look like this:
declare #version varchar(10) = '2.30.1.12'
set #version = '2.30.1.1'
if exists(select * from dbo.IsVersionNewerThan(#version,'2.30.1.12') where IsGreather >= 0)
BEGIN
print 'yes'
end
else print 'no'
Here is what I did by modifying some code I found on StackOverflow and writing some myself. This is version 1 of the code so please let me know what you think. Usage examples and test cases are in the code comments.
First create this function if not using SQL 2016 or greater and you do not have access to STRING_SPLIT:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author: <Author,,Name>
-- Create date: <Create Date,,>
-- Description: modified from https://stackoverflow.com/questions/10914576/t-sql-split-string/42000063#42000063
-- =============================================
CREATE FUNCTION [dbo].[SplitStringToRows]
(
#List VARCHAR(4000)
, #Delimiter VARCHAR(50)
)
RETURNS TABLE
AS
RETURN
(
--For testing
-- SELECT * FROM SplitStringToRows ('1.0.123','.')
-- DECLARE #List VARCHAR(MAX) = '1.0.123', #Delimiter VARCHAR(50) = '.';
WITH Casted AS
(
SELECT CAST(N'<x>' + REPLACE((SELECT REPLACE(#List,#Delimiter,N'§§Split$me$here§§') AS [*] FOR XML PATH('')),N'§§Split$me$here§§',N'</x><x>') + N'</x>' AS XML) AS SplitMe
)
SELECT ROW_NUMBER() OVER (ORDER BY (SELECT 0)) AS [Index]
, x.value(N'.',N'nvarchar(max)') AS Part
FROM Casted
CROSS APPLY SplitMe.nodes(N'/x') AS A(x)
)
Then create this function:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author: Soenhay
-- Create date: 7/1/2017
-- Description: Returns -1 if VersionStringA is less than VersionStringB.
-- Returns 0 if VersionStringA equals VersionStringB.
-- Returns 1 if VersionSTringA is greater than VersionStringB.
-- =============================================
CREATE FUNCTION dbo.CompareVersionStrings
(
#VersionStringA VARCHAR(50)
,#VersionStringB VARCHAR(50)
)
RETURNS TABLE
AS
RETURN
(
--CurrentVersion should be of the form:
--major.minor[.build[.revision]]
--This is the same as the versioning system used in c#.
--For applications the build and revision numbers will by dynamically set based on the current date and time of the build.
--Example: [assembly: AssemblyFileVersion("1.123.*")]//http://stackoverflow.com/questions/15505841/the-version-specified-for-the-file-version-is-not-in-the-normal-major-minor-b
--Each component should be between 0 and 65534 ( UInt16.MaxValue - 1 )
--Max version number would be 65534.65534.65534.65534
--For Testing
-- SELECT * FROM dbo.CompareVersionStrings('', '')
-- SELECT * FROM dbo.CompareVersionStrings('asdf.asdf', 'asdf.asdf') --returns 0
-- SELECT * FROM dbo.CompareVersionStrings('asdf', 'fdas') --returns -1
-- SELECT * FROM dbo.CompareVersionStrings('zasdf', 'fdas') --returns 1
-- SELECT * FROM dbo.CompareVersionStrings('1.0.123.123', '1.1.123.123') --Should return -1
-- SELECT * FROM dbo.CompareVersionStrings('1.0.123.123', '1.0.123.123') --Should return 0
-- SELECT * FROM dbo.CompareVersionStrings('1.1.123.123', '1.0.123.123') --Should return 1
-- SELECT * FROM dbo.CompareVersionStrings('1.0.123.123', '1.0.124.123') --Should return -1
-- SELECT * FROM dbo.CompareVersionStrings('1.0.124.123', '1.0.123.123') --Should return 1
-- SELECT * FROM dbo.CompareVersionStrings('1.0.123.123', '1.0.123.124') --Should return -1
-- SELECT * FROM dbo.CompareVersionStrings('1.0.123.124', '1.0.123.123') --Should return 1
-- SELECT * FROM dbo.CompareVersionStrings('1.0', '1.1') --Should return -1
-- SELECT * FROM dbo.CompareVersionStrings('1.0', '1.0') --Should return 0
-- SELECT * FROM dbo.CompareVersionStrings('1.1', '1.0') --Should return 1
-- Declare #VersionStringA VARCHAR(50) = '' ,#VersionStringB VARCHAR(50) = '' ;
-- Declare #VersionStringA VARCHAR(50) = '1.0.123.123' ,#VersionStringB VARCHAR(50) = '1.1.123.123' ;
-- Declare #VersionStringA VARCHAR(50) = '1.1.123.123' ,#VersionStringB VARCHAR(50) = '1.1.123.123' ;
-- Declare #VersionStringA VARCHAR(50) = '1.2.123.123' ,#VersionStringB VARCHAR(50) = '1.1.123.123' ;
-- Declare #VersionStringA VARCHAR(50) = '1.1.123' ,#VersionStringB VARCHAR(50) = '1.1.123.123' ;
-- Declare #VersionStringA VARCHAR(50) = '1.1.123.123' ,#VersionStringB VARCHAR(50) = '1.1.123' ;
-- Declare #VersionStringA VARCHAR(50) = '1.1' ,#VersionStringB VARCHAR(50) = '1.1' ;
-- Declare #VersionStringA VARCHAR(50) = '1.2' ,#VersionStringB VARCHAR(50) = '1.1' ;
-- Declare #VersionStringA VARCHAR(50) = '1.1' ,#VersionStringB VARCHAR(50) = '1.2' ;
WITH
Indexes AS
(
SELECT 1 AS [Index]
, 'major' AS Name
UNION
SELECT 2
, 'minor'
UNION
SELECT 3
, 'build'
UNION
SELECT 4
, 'revision'
)
, SplitA AS
(
SELECT * FROM dbo.SplitStringToRows(#VersionStringA, '.')
)
, SplitB AS
(
SELECT * FROM dbo.SplitStringToRows(#VersionStringB, '.')
)
SELECT
CASE WHEN major = 0 THEN
CASE WHEN minor = 0 THEN
CASE WHEN build = 0 THEN
CASE WHEN revision = 0 THEN 0
ELSE revision END
ELSE build END
ELSE minor END
ELSE major END AS Compare
FROM
(
SELECT
MAX(CASE WHEN [Index] = 1 THEN Compare ELSE NULL END) AS major
,MAX(CASE WHEN [Index] = 2 THEN Compare ELSE NULL END) AS minor
,MAX(CASE WHEN [Index] = 3 THEN Compare ELSE NULL END) AS build
,MAX(CASE WHEN [Index] = 4 THEN Compare ELSE NULL END) AS revision
FROM(
SELECT [Index], Name,
CASE WHEN A = B THEN 0
WHEN A < B THEN -1
WHEN A > B THEN 1
END AS Compare
FROM
(
SELECT
i.[Index]
,i.Name
,ISNULL(a.Part, 0) AS A
,ISNULL(b.Part, 0) AS B
FROM Indexes i
LEFT JOIN SplitA a
ON a.[Index] = i.[Index]
LEFT JOIN SplitB b
ON b.[Index] = i.[Index]
) q1
) q2
) q3
)
GO
I'll give you the most shortest answer of this.
with cte as (
select 7.11 as ver
union all
select 7.6
)
select top 1 ver from cte
order by parsename(ver, 2), parsename(cast(ver as float), 1)
Maybe converting build number to a value can help to understand the hierarchy between build versions.
DECLARE #version VARCHAR(25), #dot1 AS TINYINT, #dot2 AS TINYINT, #dot3 AS TINYINT, #MaxPower AS TINYINT, #Value AS BIGINT
SELECT #version = CAST(SERVERPROPERTY('ProductVersion') AS VARCHAR) --'14.0.1000.169' --'10.50.1600'
SELECT #dot1 = CHARINDEX('.', #version, 1)
SELECT #dot2 = CHARINDEX('.', #version, #dot1 + 1)
SELECT #dot3 = CHARINDEX('.', #version, #dot2 + 1)
SELECT #dot3 = CASE
WHEN #dot3 = 0 THEN LEN(#version) + 1
ELSE #dot3
END
SELECT #MaxPower = MAX(DotColumn) FROM (VALUES (#dot1-1), (#dot2-#dot1-1), (#dot3-#dot2-1)) AS DotTable(DotColumn)
SELECT #Value = POWER(10, #MaxPower)
--SELECT #version, #dot1, #dot2, #dot3, #MaxPower, #Value
SELECT
-- #version AS [Build],
CAST(LEFT(#version, #dot1-1) AS INT) * POWER(#Value, 3) +
CAST(SUBSTRING(#version, #dot1+1, #dot2-#dot1-1) AS INT) * POWER(#Value, 2) +
CAST(SUBSTRING(#version, #dot2+1, #dot3-#dot2-1) AS INT) * #Value +
CASE
WHEN #dot3 = LEN(#version)+1 THEN CAST(0 AS INT)
ELSE CAST(SUBSTRING(#version, #dot3+1, LEN(#version)-#dot3) AS INT)
END AS [Value]
Ispired from #Sean answer, since I needed it for 4 parts, I wrote this (and it is easily modulable for more, comment on function in end of code):
CREATE OR REPLACE FUNCTION compareversions(v1 text,v2 text)
RETURNS smallint
LANGUAGE 'plpgsql'
VOLATILE
PARALLEL UNSAFE
COST 100
AS $$
declare res int;
-- Set parts into variables (for now part 1 to 4 are used)
-- IMPORTANT: if you want to add part(s) think to add:
-- - Setting of part(s) to 0 in "Convert all empty or null parts to 0" below
-- - Proper tests in select/case below
-- IMPORTANT: do not use CAST here since it will lead to syntax error if a version or part is empty
-- v1
declare v1_1 text := split_part(v1, '.', 1);
declare v1_2 text := split_part(v1, '.', 2);
declare v1_3 text := split_part(v1, '.', 3);
declare v1_4 text := split_part(v1, '.', 4);
-- v2
declare v2_1 text := split_part(v2, '.', 1);
declare v2_2 text := split_part(v2, '.', 2);
declare v2_3 text := split_part(v2, '.', 3);
declare v2_4 text := split_part(v2, '.', 4);
begin
-- Convert all empty or null parts to 0
-- v1
if v1_1 = '' or v1_1 is null then v1_1 = '0'; end if;
if v1_2 = '' or v1_2 is null then v1_2 = '0'; end if;
if v1_3 = '' or v1_3 is null then v1_3 = '0'; end if;
if v1_4 = '' or v1_4 is null then v1_4 = '0'; end if;
-- v2
if v2_1 = '' or v2_1 is null then v2_1 = '0'; end if;
if v2_2 = '' or v2_2 is null then v2_2 = '0'; end if;
if v2_3 = '' or v2_3 is null then v2_3 = '0'; end if;
if v2_4 = '' or v2_4 is null then v2_4 = '0'; end if;
select
case
-------------
-- Compare first part:
-- - If v1_1 is inferior to v2_1 return -1 (v1 < v2),
-- - If v1_1 is superior to v2_1 return 1 (v1 > v2).
when CAST(v1_1 as int) < cast(v2_1 as int) then -1
when CAST(v1_1 as int) > cast(v2_1 as int) then 1
-------------
-------------
-- v1_1 is equal to v2_1, compare second part:
-- - If v1_2 is inferior to v2_2 return -1 (v1 < v2),
-- - If v1_2 is superior to v2_2 return 1 (v1 > v2).
when CAST(v1_2 as int) < cast(v2_2 as int) then -1
when CAST(v1_2 as int) > cast(v2_2 as int) then 1
-------------
-------------
-- v1_1 is equal to v2_1 and v1_2 is equal to v2_2, compare third part:
-- - If v1_3 is inferior to v2_3 return -1 (v1 < v2),
-- - If v1_3 is superior to v2_3 return 1 (v1 > v2).
when CAST(v1_3 as int) < cast(v2_3 as int) then -1
when CAST(v1_3 as int) > cast(v2_3 as int) then 1
-------------
-------------
-- Etc..., continuing with fourth part:
when CAST(v1_4 as int) < cast(v2_4 as int) then -1
when CAST(v1_4 as int) > cast(v2_4 as int) then 1
-------------
-- All parts are equals, meaning v1 == v2, return 0
else 0
end
into res;
return res;
end;
$$;
;
COMMENT ON FUNCTION compareversions(v1 text,v2 text)
IS 'Function to compare 2 versions as strings, versions can have from 1 to 4 parts (e.g. "1", "2.3", "3.4.5", "5.6.78.9") but it is easy to add a part.
A version having less than 4 parts is considered having its last part(s) set to 0, i.e. "2.3" is considered as "2.3.0.0" so that comparing "1.2.3" to "1.2.3.0" returns "equal"). Indeed we consider first part is always major, second minor, etc ... whatever the number of part for any version.
Function returns:
- -1 when v1 < v2
- 1 when v1 > v2
- 0 when v1 = v2
And, according to return value:
- To compare if v1 < v2 check compareversions(v1, v2) == -1
- To compare if v1 > v2 check compareversions(v1, v2) == 1
- To compare if v1 == v2 check compareversions(v1, v2) == 0
- To compare if v1 <= v2 check compareversions(v1, v2) <= 0
- To compare if v1 >= v2 check compareversions(v1, v2) >= 0'
;
With this you can also for example compare a version "1.2" with "1.2.1" (will return -1, v1 < v2) as "1.2" will be considered as "1.2.0", it is not an usual check but in case during time a digit is added to version a "1.2" will actually be considered equal to "1.2.0".
And it's also easily modulable for another version format, for X.Y-Z for example, v1_1, etc... will be (not tested but you got the idea):
-- v1_1 = X
declare v1_1 text := split_part(v1, '.', 1);
-- tmp = Y-Z
declare tmp text := split_part(v1, '.', 2);
-- v1_2 = Y
declare v1_2 text := split_part(tmp, '-', 1);
-- v1_3 = Z
declare v1_3 text := split_part(tmp, '-', 2);
-- do the same for v2
#MartinSmith answer works best for up-to 5 decimals but if more than that (which might be rare). Here is what I could have done:
DECLARE #AppVersion1 VARCHAR(20) = '2.7.2.2.3.1'
DECLARE #AppVersion2 VARCHAR(20) = '2.7.2.2.4'
DECLARE #V1 AS INT = CASE WHEN LEN(#AppVersion1) < LEN(#AppVersion2) THEN CAST(REPLACE(#AppVersion2,'.','') AS INT) ELSE CAST(REPLACE(#AppVersion1,'.','') AS INT) END;
DECLARE #V2 AS INT = CASE WHEN LEN(#AppVersion1) < LEN(#AppVersion2) THEN CAST(REPLACE(#AppVersion1,'.','') AS INT) ELSE CAST(REPLACE(#AppVersion2,'.','') AS INT) END;
IF(LEN(#V2)< LEN(#V1))
BEGIN
SET #V2 = CAST( LTRIM(CAST(#V2 AS VARCHAR)) + ISNULL(REPLICATE('0',LEN(#V1)-LEN(#V2)),'') AS INT);
END;
SELECT CASE WHEN #V1 > #V2 THEN 'Y' ELSE 'N' END

Getting average from 3 columns in SQL Server

I have a table with 3 columns (smallint) in SQL Server 2005.
Table Ratings
ratin1 smallint,
ratin2 smallint
ratin3 smallint
These columns can have values from 0 to 5.
How can I select the average value of these fields, but only compare fields where the value is greater then 0.
So if the column values are 1, 3 ,5 - the average has to be 3.
if the values are 0, 3, 5 - The average has to be 4.
This is kind of quick and dirty, but it will work...
SELECT (ratin1 + ratin2 + ratin3) /
((CASE WHEN ratin1 = 0 THEN 0 ELSE 1 END) +
(CASE WHEN ratin2 = 0 THEN 0 ELSE 1 END) +
(CASE WHEN ratin3 = 0 THEN 0 ELSE 1 END) +
(CASE WHEN ratin1 = 0 AND ratin2 = 0 AND ratin3 = 0 THEN 1 ELSE 0 END) AS Average
#mwigdahl - this breaks if any of the values are NULL. Use the NVL (value, default) to avoid this:
Sum columns with null values in oracle
Edit: This only works in Oracle. In TSQL, try encapsulating each field with an ISNULL() statement.
There should be an aggregate average function for sql server.
http://msdn.microsoft.com/en-us/library/ms177677.aspx
This is trickier than it looks, but you can do this:
SELECT dbo.MyAvg(ratin1, ratin2, ratin3) from TableRatings
If you create this function first:
CREATE FUNCTION [dbo].[MyAvg]
(
#a int,
#b int,
#c int
)
RETURNS int
AS
BEGIN
DECLARE #result int
DECLARE #divisor int
SELECT #divisor = 3
IF #a = 0 BEGIN SELECT #divisor = #divisor - 1 END
IF #b = 0 BEGIN SELECT #divisor = #divisor - 1 END
IF #c = 0 BEGIN SELECT #divisor = #divisor - 1 END
IF #divisor = 0
SELECT #result = 0
ELSE
SELECT #result = (#a + #b + #c) / #divisor
RETURN #Result
END
select
(
select avg(v)
from (values (Ratin1), (Ratin2), (Ratin3)) as value(v)
) as average
You can use the AVG() function. This will get the average for a column. So, you could nest a SELECT statement with the AVG() methods and then SELECT these values.
Pseudo:
SELECT col1, col2, col3
FROM (
SELECT AVG(col1) AS col1, AVG(col2) AS col2, AVG(col3) AS col3
FROM table
) as tbl
WHERE col1 IN (0, 3, 5)
etc.