I used this function to extract decimal numbers from a string:
ALTER Function [dbo].[udf_ExtractNumber] (#String nvarchar(256))
RETURNS nvarchar(max)
AS
BEGIN
DECLARE #AlphaNumeric varchar(256)
,#Res varchar(256)
SET #AlphaNumeric = #String
SET #Res = NULL
WHILE (PATINDEX('%[0-9]%', #AlphaNumeric) > 0 )
BEGIN
IF (PATINDEX('%[0-9]%', #AlphaNumeric) >0 AND PATINDEX('%[0-9]%', #AlphaNumeric) < CHARINDEX(',', #AlphaNumeric))
BEGIN
SET #Res = CONCAT(#Res ,SUBSTRING(#AlphaNumeric, PATINDEX('%[0-9]%', #AlphaNumeric), 1) )
SET #AlphaNumeric = RIGHT(#AlphaNumeric,len(#AlphaNumeric)- PATINDEX('%[0-9]%', #AlphaNumeric))
END
ELSE IF (CHARINDEX(',', #AlphaNumeric) >0 AND CHARINDEX(',', #AlphaNumeric) < PATINDEX('%[0-9]%', #AlphaNumeric))
BEGIN
SET #Res = CONCAT(#Res ,SUBSTRING(#AlphaNumeric, CHARINDEX(',', #AlphaNumeric), 1) )
SET #AlphaNumeric = RIGHT(#AlphaNumeric,len(#AlphaNumeric)- CHARINDEX(',', #AlphaNumeric))
END
ELSE IF (PATINDEX('%[0-9]%', #AlphaNumeric) >0)
BEGIN
SET #Res = CONCAT(#Res, SUBSTRING(#AlphaNumeric, PATINDEX('%[0-9]%', #AlphaNumeric), 1) )
SET #AlphaNumeric = RIGHT(#AlphaNumeric,len(#AlphaNumeric)- PATINDEX('%[0-9]%', #AlphaNumeric))
END
ELSE IF (CHARINDEX(',', #AlphaNumeric) >0 )
BEGIN
SET #Res = CONCAT(#Res,SUBSTRING(#AlphaNumeric, CHARINDEX(',', #AlphaNumeric), 1))
SET #AlphaNumeric = RIGHT(#AlphaNumeric,len(#AlphaNumeric)- CHARINDEX(',', #AlphaNumeric))
END
END
Return #Res
This is working fine, output is exactly what i want.
It converts for example "adsfadf 18,12 adfasdsfa" to 18,12
However, when I want to work with the number I cannot convert it to a float.
Dividing or multiplying it gives the following error:
Conversion failed when converting the nvarchar value '7,5' to data type int.
Based on comments of Ali Fidenli, I adjust the last part of the code to get it working. Thanks
END
Return replace(#Res,',','.')
Related
How to generate a matrix of random numbers where the values in each row add up to X in T-SQL?
The solution matrix should be dynamic:
User can specify number of columns to be returned in the result
User can specify number of rows to be returned in the result
Each row must sum to X (eg. 1)
create proc RandomNumberGenerator
(
#rows int
, #cols int
, #rowsumtotal float
)
as
....
First create a UDF...
CREATE FUNCTION [dbo].[_ex_fn_SplitToTable] (#str varchar(5000), #sep varchar(1) = null)
RETURNS #ReturnVal table (n int, s varchar(5000))
AS
/*
Alpha Test
-----------
select * from [dbo].[_ex_fn_SplitToTable_t2]('a b c d e',' ')
*/
BEGIN
if #sep = ' '
begin
set #sep = CHAR(167)
set #str = REPLACE(#str,' ',CHAR(167))
end
declare #str2 varchar(5000)
declare #sep2 varchar(1)
if LEN(ISNULL(#sep,'')) = 0
begin
declare #i int
set #i = 0
set #str2 = ''
declare #char varchar(1)
startloop:
set #i += 1
--print #i
set #char = substring(#str,#i,1)
set #str2 = #str2 + #char + ','
if LEN(#str) <= #i
goto exitloop
goto startloop
exitloop:
set #str2 = left(#str2,LEN(#str2) - 1)
set #sep2 = ','
--print #str2
end
else
begin
set #str2 = #str
set #sep2 = #sep
end
;WITH Pieces(n, start, stop) AS (
SELECT 1, 1, CHARINDEX(#sep2, #str2)
UNION ALL
SELECT n + 1, stop + 1, CHARINDEX(#sep2, #str2, stop + 1)
FROM Pieces
WHERE stop > 0
)
insert into #ReturnVal(n,s)
SELECT n,
SUBSTRING(#str2, start, CASE WHEN stop > 0 THEN stop-start ELSE 5000 END) AS s
FROM Pieces option (maxrecursion 32767)
RETURN
END
GO
Then, create this stored proc...
CREATE PROC [dbo].[RandomNumberGenerator]
(
#Pockets int = 6,
#SumTo float = 100,
#i_iterations int = 100
)
/*
ALPHA TEST
----------
exec RandomNumberGenerator 10, 100, 500
*/
AS
if object_id('tempdb..#_Random_00') is not null drop table #_Random_00
declare #columnstring varchar(max) = (SELECT REPLICATE('c ',#Pockets) as Underline)
print #columnstring
if object_id('tempdb..#_Random_columns') is not null drop table #_Random_columns
select s+CONVERT(varchar,dbo.PadLeft(convert(varchar,n),'0',3)) cols
into #_Random_columns
from [dbo].[_ex_fn_SplitToTable](#columnstring,' ') where LEN(s) > 0
-- ===========================
--select * from #_Random_columns
-- ===========================
declare #columns_sql varchar(max)
set #columns_sql =
(
select distinct
stuff((SELECT distinct + cast(cols as varchar(50)) + ' float, '
FROM (
select cols
from #_Random_columns
) t2
--where t2.n = t1.n
FOR XML PATH('')),3,0,'')
from (
select cols
from #_Random_columns
) t1
)
set #columns_sql = LEFT(#columns_sql,LEN(#columns_sql) - 1)
print #columns_sql
declare #sql varchar(max)
set #sql = 'if object_id(''tempdb..##_proctable_Random_01'') is not null drop table ##_proctable_Random_01 '
print #sql
execute(#sql)
set #sql = 'create table ##_proctable_Random_01 (rowid int,' + #columns_sql + ')'
print #sql
execute(#sql)
declare #TotalOfRand float
declare #i_inner int
declare #i_outer int
set #i_outer = 0
start_outer:
set #i_outer = #i_outer + 1
set #i_inner = 0
declare #sumstring varchar(max)
set #sumstring = ''
start_inner:
set #i_inner = #i_inner+1
set #sumstring = #sumstring + CONVERT(varchar, rand()) + ','
if #i_inner >= #Pockets
goto exit_inner
goto start_inner
exit_inner:
set #TotalOfRand = ( select sum(convert(float,s)) from dbo._ex_fn_SplitToTable(#sumstring,',') )
declare #sumstring_quotient varchar(max)
set #sumstring_quotient = replace(#sumstring,',', '/' + Convert(varchar,#TotalOfRand) + '*' + convert(varchar,#SumTo) + ',')
set #sumstring_quotient = LEFT(#sumstring_quotient,len(#sumstring_quotient) - 1)
print #sumstring_quotient
set #sql = '
insert into ##_proctable_Random_01
select
( select count(*) + 1 from ##_proctable_Random_01 ) rowid,' + #sumstring_quotient
execute(#sql)
if #i_outer >= #i_iterations
goto exit_outer
goto start_outer
exit_outer:
select * from ##_proctable_Random_01
drop table ##_proctable_Random_01
GO
how to remove leading zero from this
number RESULT WOULD BE LIKE THIS
00000.9 .9
A0001.1 A1.1
G0101.3 G101.3
00808.8 808.8
J0000.5 J.5
declare #input varchar(10);
declare #output varchar(10);
set #input = '00000.9';
while ((ISNUMERIC(substring(#input,1,1)) = 0) or (substring(#input,1,1) = '0'))
begin
if substring(#input,1,1) = '0'
begin
set #input = substring(#input,2,len(#input) )
end
else
if ISNUMERIC(substring(#input,1,1)) = 0
begin
set #output = substring(#input,1,1);
set #input = substring(#input,2,len(#input))
end
end
if LEN(#output) > 0
set #input = #output + #input
select #input
#input is your input
ALTER FUNCTION NUMBER(#NUMBER VARCHAR(7))
RETURNS VARCHAR(7)
AS
BEGIN
DECLARE #NUM VARCHAR(1)
DECLARE #NUM1 VARCHAR(7)
SET #NUM= SUBSTRING(#NUMBER,1,1)
IF(#NUM LIKE '[A-Z%]')
BEGIN
SET #NUM1=#NUM+''+CAST(CONVERT(FLOAT,SUBSTRING(#NUMBER,2,7),2)AS VARCHAR(7))
END
ELSE
BEGIN
SET #NUM1=LTRIM(STR(cast(#NUMBER as float),case when len(cast(#NUMBER as float)) > 7 then 7 else len(cast(#NUMBER as float)) end,1))
END
RETURN #NUM
END
my problem is pretty simple. I get a value from a sql select which looks like this:
ARAMAUBEBABRBGCNDKDEEEFOFIFRGEGRIEISITJPYUCAKZKG
and I need it like this:
AR,AM,AU,BE,BA,BR,BG,CN,DK,DE,EE,FO,FI,FR,GE,GR,IE,IS,IT,JP,YU,CA,KZ,KG
The length is different in each dataset.
I tried it with format(), stuff() and so on but nothing brought me the result I need.
Thanks in advance
With a little help of a numbers table and for xml path.
-- Sample table
declare #T table
(
Value nvarchar(100)
)
-- Sample data
insert into #T values
('ARAMAU'),
('ARAMAUBEBABRBGCNDKDEEEFOFIFRGEGRIEISITJPYUCAKZKG')
declare #Len int
set #Len = 2;
select stuff(T2.X.value('.', 'nvarchar(max)'), 1, 1, '')
from #T as T1
cross apply (select ','+substring(T1.Value, 1+Number*#Len, #Len)
from Numbers
where Number >= 0 and
Number < len(T1.Value) / #Len
order by Number
for xml path(''), type) as T2(X)
Try on SE-Data
Time to update your resume.
create function DontDoThis (
#string varchar(max),
#count int
)
returns varchar(max)
as
begin
declare #result varchar(max) = ''
declare #token varchar(max) = ''
while DATALENGTH(#string) > 0
begin
select #token = left(#string, #count)
select #string = REPLACE(#string, #token, '')
select #result += #token + case when DATALENGTH(#string) = 0 then '' else ',' end
end
return #result
end
Call:
declare #test varchar(max) = 'ARAMAUBEBABRBGCNDKDEEEFOFIFRGEGRIEISITJPYUCAKZKG'
select dbo.DontDoThis(#test, 2)
gbn's comment is exactly right, if not very diplomatic :) TSQL is a poor language for string manipulation, but if you write a CLR function to do this then you will have the best of both worlds: .NET string functions called from pure TSQL.
I believe this is what QQping is looking for.
-- select .dbo.DelineateEachNth('ARAMAUBEBABRBGCNDKDEEEFOFIFRGEGRIEISITJPYUCAKZKG',2,',')
create function DelineateEachNth
(
#str varchar(max), -- Incoming String to parse
#length int, -- Length of desired segment
#delimiter varchar(100) -- Segment delimiter (comma, tab, line-feed, etc)
)
returns varchar(max)
AS
begin
declare #resultString varchar(max) = ''
-- only set delimiter(s) when lenght of string is longer than desired segment
if LEN(#str) > #length
begin
-- continue as long as there is a remaining string to parse
while len(#str) > 0
begin
-- as long as know we still need to create a segment...
if LEN(#str) > #length
begin
-- build result string from leftmost segment length
set #resultString = #resultString + left(#str, #length) + #delimiter
-- continually shorten result string by current segment
set #str = right(#str, len(#str) - #length)
end
-- as soon as the remaining string is segment length or less,
-- just use the remainder and empty the string to close the loop
else
begin
set #resultString = #resultString + #str
set #str = ''
end
end
end
-- if string is less than segment length, just pass it through
else
begin
set #resultString = #str
end
return #resultString
end
With a little help from Regex
select Wow=
(select case when MatchIndex %2 = 0 and MatchIndex!=0 then ',' + match else match end
from dbo.RegExMatches('[^\n]','ARAMAUBEBABRBGCNDKDEEEFOFIFRGEGRIEISITJPYUCAKZKG',1)
for xml path(''))
The question is self explanatory. Could you please point out a way to put spaces between each capital letter of a string.
SELECT dbo.SpaceBeforeCap('ThisIsATestString')
would result in
This Is A Test String.
This will add spaces only if the previous and next character is lowercase. That way 'MyABCAnalysis' will be 'My ABC Analysis'.
I added a check for a previous space too. Since some of our strings are prefixed with 'GR_' and some also contain underscores, we can use the replace function as follows:
select dbo.GR_SpaceBeforeCap(replace('GR_ABCAnalysis_Test','_',' '))
Returns 'GR ABC Analysis Test'
CREATE FUNCTION GR_SpaceBeforeCap (
#str nvarchar(max)
)
returns nvarchar(max)
as
begin
declare
#i int, #j int
, #cp nchar, #c0 nchar, #c1 nchar
, #result nvarchar(max)
select
#i = 1
, #j = len(#str)
, #result = ''
while #i <= #j
begin
select
#cp = substring(#str,#i-1,1)
, #c0 = substring(#str,#i+0,1)
, #c1 = substring(#str,#i+1,1)
if #c0 = UPPER(#c0) collate Latin1_General_CS_AS
begin
-- Add space if Current is UPPER
-- and either Previous or Next is lower
-- and Previous or Current is not already a space
if #c0 = UPPER(#c0) collate Latin1_General_CS_AS
and (
#cp <> UPPER(#cp) collate Latin1_General_CS_AS
or #c1 <> UPPER(#c1) collate Latin1_General_CS_AS
)
and #cp <> ' '
and #c0 <> ' '
set #result = #result + ' '
end -- if #co
set #result = #result + #c0
set #i = #i + 1
end -- while
return #result
end
Assuming SQL Server 2005 or later, this modified from code taken here: http://www.kodyaz.com/articles/case-sensitive-sql-split-function.aspx
CREATE FUNCTION SpaceBeforeCap
(
#str nvarchar(max)
)
returns nvarchar(max)
as
begin
declare #i int, #j int
declare #returnval nvarchar(max)
set #returnval = ''
select #i = 1, #j = len(#str)
declare #w nvarchar(max)
while #i <= #j
begin
if substring(#str,#i,1) = UPPER(substring(#str,#i,1)) collate Latin1_General_CS_AS
begin
if #w is not null
set #returnval = #returnval + ' ' + #w
set #w = substring(#str,#i,1)
end
else
set #w = #w + substring(#str,#i,1)
set #i = #i + 1
end
if #w is not null
set #returnval = #returnval + ' ' + #w
return ltrim(#returnval)
end
This can then be called just as you have suggested above.
This function combines previous answers. Selectively choose to preserve adjacent CAPS:
CREATE FUNCTION SpaceBeforeCap (
#InputString NVARCHAR(MAX),
#PreserveAdjacentCaps BIT
)
RETURNS NVARCHAR(MAX)
AS
BEGIN
DECLARE
#i INT, #j INT,
#previous NCHAR, #current NCHAR, #next NCHAR,
#result NVARCHAR(MAX)
SELECT
#i = 1,
#j = LEN(#InputString),
#result = ''
WHILE #i <= #j
BEGIN
SELECT
#previous = SUBSTRING(#InputString,#i-1,1),
#current = SUBSTRING(#InputString,#i+0,1),
#next = SUBSTRING(#InputString,#i+1,1)
IF #current = UPPER(#current) COLLATE Latin1_General_CS_AS
BEGIN
-- Add space if Current is UPPER
-- and either Previous or Next is lower or user chose not to preserve adjacent caps
-- and Previous or Current is not already a space
IF #current = UPPER(#current) COLLATE Latin1_General_CS_AS
AND (
#previous <> UPPER(#previous) COLLATE Latin1_General_CS_AS
OR #next <> UPPER(#next) collate Latin1_General_CS_AS
OR #PreserveAdjacentCaps = 0
)
AND #previous <> ' '
AND #current <> ' '
SET #result = #result + ' '
END
SET #result = #result + #current
SET #i = #i + 1
END
RETURN #result
END
GO
SELECT dbo.SpaceBeforeCap('ThisIsASampleDBString', 1)
GO
SELECT dbo.SpaceBeforeCap('ThisIsASampleDBString', 0)
CLR and regular expressions or 26 replace statements a case sensitive collate clause and a trim.
Another strategy would be to check the ascii value of each character:
create function SpaceBeforeCap
(#str nvarchar(max))
returns nvarchar(max)
as
begin
declare #result nvarchar(max)= left(#str, 1),
#i int = 2
while #i <= len(#str)
begin
if ascii(substring(#str, #i, 1)) between 65 and 90
select #result += ' '
select #result += substring(#str, #i, 1)
select #i += 1
end
return #result
end
/***
SELECT dbo.SpaceBeforeCap('ThisIsATestString')
**/
To avoid loops altogether, use of a tally table can help here. If you are running on SQL 2022, then the generate_series function can remove even this dependency. This method will be significantly faster than iterating through a loop.
create function core.ufnAddSpaceBeforeCapital
(
#inputString nvarchar(max)
)
returns nvarchar(max)
as
begin
declare #outputString nvarchar(max)
select
#outputString = string_agg(iif(t.value = 1, upper(substring(#inputString,t.value,1)),iif(ascii(substring(#inputString,t.value,1)) between 65 and 90, ' ','') + substring(#inputString,t.value,1)),'')
from
generate_series(1,cast(len(#inputString) as int)) t
return #outputString
end
The scalar function is not inlineable, so I've provided an alternative inline table-valued function if that's what you need.
create function core.ufnAddSpaceBeforeCapitalITVF
(
#inputString nvarchar(max)
)
returns table
as
return
(
select
string_agg(iif(t.value = 1, upper(substring(#inputString,t.value,1)),iif(ascii(substring(#inputString,t.value,1)) between 65 and 90, ' ','') + substring(#inputString,t.value,1)),'') as outputString
from
generate_series(1,cast(len(#inputString) as int)) t
)
end
While I really like the char looping answers I was not thrilled with the performance. I have found this performs in a fraction of the time for my use case.
CREATE function SpaceBeforeCap
(#examine nvarchar(max))
returns nvarchar(max)
as
begin
DECLARE #index as INT
SET #index = PatIndex( '%[^ ][A-Z]%', #examine COLLATE Latin1_General_BIN)
WHILE #index > 0 BEGIN
SET #examine = SUBSTRING(#examine, 1, #index) + ' ' + SUBSTRING(#examine, #index + 1, LEN(#examine))
SET #index = PatIndex( '%[^ ][A-Z]%', #examine COLLATE Latin1_General_BIN)
END
RETURN LTRIM(#examine)
end
This makes use of the fact that
case sensitive pattern search only works in some collations. The character class [^ ] means anything except space, so as we add the missing spaces we match farther into the string until it is complete.
To resolve the issue.
There are two meanings Time: 12:20 and 23:55. How can add the values that-be at the outlet was 36:15.
Or how to keep these values in dB (Time) Time except that, were it possible addition?
Firebird's data type TIME allows range between 00:00:00 and 24:00:00 only.
If you want to store arbitrary amount of time (say, in seconds) use INTEGER or NUMERIC datatype. Then convert it into time string format if needed.
You can use TIMESTAMP in dialect 3
With this you can add 2 times.
i have code here convert seconds in integer
CREATE PROCEDURE P_CONVERT_TIME (
V_TIME_INT INTEGER
)
RETURNS (
V_TIME_STR VARCHAR(20)
)
AS
DECLARE VARIABLE v_max_trans_hour integer;
DECLARE VARIABLE v_max_trans_min integer;
DECLARE VARIABLE v_max_trans_sec integer;
DECLARE VARIABLE v_max_trans_sec_gross integer;
BEGIN
v_max_trans_sec = cast(v_Time_Int as integer);
v_max_trans_hour = coalesce(div(v_max_trans_sec, 3600), 0);
if (v_max_trans_hour > 0) then
v_max_trans_sec = v_max_trans_sec - (3600 * v_max_trans_hour);
v_max_trans_min = coalesce(div(v_max_trans_sec, 60), 0);
if (v_max_trans_min > 0) then
v_max_trans_sec = v_max_trans_sec - (60 * v_max_trans_min);
if (v_max_trans_hour > 0) then begin
if (v_max_trans_hour < 10) then begin
V_Time_Str ='0'||v_max_trans_hour||':'; end else
V_Time_Str=v_max_trans_hour||':';
end else V_Time_Str='00:';
if (v_max_trans_min > 0) then begin
if (v_max_trans_min <10) then begin
V_Time_Str =V_Time_Str ||'0'||v_max_trans_min||':'; end else
V_Time_Str =V_Time_Str ||v_max_trans_min||':';
end else V_Time_Str =V_Time_Str ||'00:';
if (v_max_trans_sec > 0) then begin
if (v_max_trans_sec <10) then begin
V_Time_Str =V_Time_Str ||'0'|| v_max_trans_sec; end else
V_Time_Str =V_Time_Str || v_max_trans_sec;
end else V_Time_Str =V_Time_Str ||'00';
suspend;
END
;