convert varchar to int in select statement using patindex - sql-server

My query is for convert varchar into string,
select top(5)'Insert into jobs(minexperience,maxexperience)values('+
cast(substring(Experience as varchar(50)),0,patindex('%to%',Experience))*365*24*60*60,
cast(substring(Experience as
varchar(50)),patindex('%to%',Experience)+2,patindex('%Years%',Experience)-patindex('%to%',Experience)-2)*365*24*60*60+')'
from requirementsdetailsfororganization
In my below query i have an error "Incorrect syntax near the keyword 'AS'."
I want to convert string to integer.
Any Help?

Possible this helpful for you -
SELECT TOP(5) 'INSERT INTO dbo.jobs(minexperience,maxexperience) VALUES(' +
CAST(SUBSTRING(
CAST(r.Experience AS VARCHAR(50))
, 0
, r.ToExperience) * 31536000
AS VARCHAR(50))
+ ',' +
CAST(SUBSTRING(
CAST(r.Experience AS VARCHAR(50))
, r.ToExperience + 2
, patindex('%Years%', r.Experience) - r.ToExperience - 2) * 31536000
AS VARCHAR(50))
+')'
FROM (
SELECT
r.Experience
, ToExperience = PATINDEX('%to%', r.Experience)
FROM dbo.requirementsdetailsfororganization r
) r

Related

Snowflake convert string into output

select ' \''||
CAST(NVL(X.TYPE,'') AS VARCHAR(50))||'\
\''||CAST(NVL(X.ID_1,'') AS VARCHAR(50))||'\
- \''||
---CAST(NVL(X.ID_2,'') AS VARCHAR(50))
CASE WHEN X.ID_2 IS NOT NULL
THEN X.ID_2
WHEN X.ID_2 IS NULL
THEN 'NULL' END
||'\ '
from
( select ....)
select query returns value for three columns.
Above code gives o/p as 'R'32 - 'NULL
Expected is 'R 32 - NULL'
Can someone help
Using CONCAT and COALESCE:
SELECT *,
CONCAT('\'',COALESCE(X.TYPE,''), ' ' ,
COALESCE(X.ID_1::TEXT, ''), ' - ' ,
COALESCE(X.ID_2::TEXT, 'NULL'), '\'') AS res
FROM (SELECT 'R' AS TYPE, 32::INT AS ID_1, NULL AS ID_2) AS X;
Output:
#Rahul, I believe you are looking for something like this? The escaped apostrophes were the culprit from Lukasz's answer.
SELECT
CONCAT(
COALESCE(X.TYPE,'')
, CHAR(32) /* <-- ADDS A SPACE */
, COALESCE(X.ID_1::TEXT, '')
, CHAR(32), CHAR(45), CHAR(32) /* <-- ADDS A SPACE DASH SPACE */
, COALESCE(X.ID_2::TEXT, 'NULL')
) AS res
FROM (SELECT 'R' AS TYPE, 32::INT AS ID_1, NULL AS ID_2) AS X
;
Returns:
R 32 - NULL

Syntax error in my user defined function?

I creating a function and I have a red error line under the BEGIN keyword and I can't figure out what is wrong with this query?
USE PR
GO
CREATE FUNCTION fnInsCosts
(#NoDependents int)
RETURNS TABLE
BEGIN
RETURN
(SELECT
EmpName,
SUM(BaseCost) AS TotBaseCost,
SUM(SpouseIns) AS TotSpouseCost,
SUM(DepIns) AS TotDepCost,
SUM(DentalCost) AS TotDentalCost,
SUM(SUM(BaseCost) + SUM(SpouseIns) + SUM(DepIns) + SUM(DentalCost)) AS TotalInsCost
FROM
vwPayroll
WHERE
Dependants = #NoDependents
GROUP BY
EmpName)
END;
try
CREATE FUNCTION dbo.fnInsCosts
(#NoDependents int)
RETURNS TABLE
AS
RETURN (
SELECT EmpName, SUM(BaseCost) AS TotBaseCost, SUM(SpouseIns) AS TotSpouseCost
, SUM(DepIns) AS TotDepCost, SUM(DentalCost) AS TotDentalCost
, SUM(SUM(BaseCost) + SUM(SpouseIns) + SUM(DepIns) + SUM(DentalCost)) AS TotalInsCost
FROM vwPayroll
WHERE Dependants = #NoDependents
GROUP BY EmpName
)

SQL Server build dynamic sql

I have a temp table called #temp, and I need to get all the CDate column from that table, to build a string.
The CDate list in that table is (20171209, 20171210....20171223)
I expected to see
'A.[20171209] as [20171209], A.[20171210] as [20171210],
A.[20171211] as [20171211], A.[20171212] as [20171212],
A.[20171213] as [20171213], A.[20171214] as [20171214],
A.[20171215] as [20171215], A.[20171216] as [20171216],
A.[20171217] as [20171217], A.[20171218] as [20171218],
A.[20171219] as [20171219], A.[20171220] as [20171220],
A.[20171221] as [20171221], A.[20171222] as [20171222],
A.[20171223] as [20171223], '
however the result I got is missing the first date , ie 'A.[20171209] as [20171209]'
Here is my code:
SELECT
#col2 = ISNULL(#col2 + 'A.' + QUOTENAME(CDate) + ' as ' + QUOTENAME(CDate) + ', ' , '')
FROM
(SELECT DISTINCT CDate FROM #temp) AS tmp;
Your current approach will not work in some cases, it is an undocumented feature, always use For Xml path to concatenating the rows into csv.
SET #col2 = stuff((SELECT ', A.' + Quotename(CDate) + ' as '
+ Quotename(CDate)
FROM (SELECT DISTINCT CDate
FROM #temp) a
FOR xml path('')),1,1,'')

select a particular string from a semi-colon delimited list [duplicate]

This question already has answers here:
Using T-SQL, return nth delimited element from a string
(14 answers)
Closed 6 years ago.
I want to extract a string which has semi-colon as a delimiter. I tried using Substring, Charindex and Left function. But I'm not able to get the desired result. Below is my select statement. Output result must be "Unsure how to perform task. Meter read 10 in office before testing". Thanks
Declare #string Varchar(max)='Sampling:45;Traveling:30;CalibratedNo;uncalibratedReason:: ' +
'Unsure how to perform task. Meter read 10 in office before ' +
'testing.;pH1:6.5;pH2:6.5;Dis.Oxygen1:7.4'
Select SubString(#string, (CHARINDEX('uncalibratedReason:', #string, 0) + 19),
(CharIndex('uncalibratedReason:', LEFT(#string, (LEN(#string) -
(CharIndex(';', #string, 0)))), 0) - 0)) As New
Try it like this:
Declare #string Varchar(max) = 'Sampling:45;Traveling:30;CalibratedNo;uncalibratedReason:Unsure how to perform task. Meter read 10 in office before testing.;pH1:6.5;pH2:6.5;Dis.Oxygen1:7.4';
SELECT CAST('<x>' + REPLACE(#string,';','</x><x>') + '</x>' AS XML).value('x[4]','nvarchar(max)')
The result is:
uncalibratedReason:Unsure how to perform task. Meter read 10 in office before testing.
You can take away the leading uncalibratedReason: simply with SUBSTRING and CHARINDEX looking for : if you need this.
UPDATE
Here is the full code:
DECLARE #result NVARCHAR(MAX)=
(SELECT CAST('<x>' + REPLACE(#string,';','</x><x>') + '</x>' AS XML).value('x[4]','nvarchar(max)'));
SELECT SUBSTRING(#result,CHARINDEX(':',#result)+1,10000)
UPDATE 2: Find position by starting string
DECLARE #result NVARCHAR(MAX)=
(SELECT CAST('<x>' + REPLACE(#string,';','</x><x>') + '</x>' AS XML).value('(x[substring(.,1,string-length("uncalibratedReason:")) eq "uncalibratedReason:"])[1]','nvarchar(max)'));
SELECT SUBSTRING(#result,CHARINDEX(':',#result)+1,10000)
UPDATE 3 The ultimative solution :-)
Declare #string Varchar(max) = 'Sampling:45;Traveling:30;CalibratedNo;uncalibratedReason:Unsure how to perform task. Meter read 10 in office before testing.;pH1:6.5;pH2:6.5;Dis.Oxygen1:7.4';
WITH Casted(ThePart) AS
(
SELECT Node.value('.','nvarchar(max)')
FROM
(
SELECT CAST('<x>' + REPLACE(#string,';','</x><x>') + '</x>' AS XML)
) AS tbl(AsXML)
CROSS APPLY AsXML.nodes('/x') AS The(Node)
)
,Splitted(SpecificPart) AS
(
SELECT CAST('<x>' + REPLACE(ThePart,':','</x><x>') + '</x>' AS XML)
FROM Casted
)
SELECT SpecificPart.value('x[1]','nvarchar(max)') AS Caption
,SpecificPart.value('x[2]','nvarchar(max)') AS Data
FROM Splitted
The result
Caption Data
CalibratedNo NULL
Dis.Oxygen1 7.4
pH1 6.5
pH2 6.5
Sampling 45
Traveling 30
uncalibratedReason Unsure how to perform task. Meter read 10 in office before testing.
Shnugo anwser very cool. (UpVote)
However, this UDF Parser returns the sequence and value
Declare #string Varchar(max)='Sampling:45;Traveling:30;CalibratedNo;uncalibratedReason:: ' +
'Unsure how to perform task. Meter read 10 in office before ' +
'testing.;pH1:6.5;pH2:6.5;Dis.Oxygen1:7.4'
Select * from [dbo].[udf-Str-Parse](#String,';')
--Where Key_PS = 5
--Where Key_Value Like '%:%'
--Where Key_Value Like 'pH1%'
Returns
Key_PS Key_Value
1 Sampling:45
2 Traveling:30
3 CalibratedNo
4 uncalibratedReason:: Unsure how to perform task. Meter read 10 in office before testing.
5 pH1:6.5
6 pH2:6.5
7 Dis.Oxygen1:7.4
The UDF
CREATE FUNCTION [dbo].[udf-Str-Parse] (#String varchar(max),#Delimeter varchar(10))
--Usage: Select * from [dbo].[udf-Str-Parse]('Dog,Cat,House,Car',',')
-- Select * from [dbo].[udf-Str-Parse]('John Cappelletti was here',' ')
Returns #ReturnTable Table (Key_PS int IDENTITY(1,1), Key_Value varchar(max))
As
Begin
Declare #XML xml;Set #XML = Cast('<x>' + Replace(#String,#Delimeter,'</x><x>')+'</x>' as XML)
Insert Into #ReturnTable Select ltrim(rtrim(String.value('.', 'varchar(max)'))) FROM #XML.nodes('x') as T(String)
Return
End

split alpha and numeric using sql

I have a table and it has a 3 columns. The first column is the data that contains value(numeric) and unit(percentage and etc..), the second column is numeric column, the third is Unit column. What I want to do is split the numeric and the unit from the first column then put those split-ted data to its designated column.
Here is my table:
I tried this function:SO link here..., it really does splitting alpha and numeric but then I'm new in using SQL Function, my problem there is the parameter must be in string STRING, so what I did is change it to Sub Query but it gives me error.
Sample COde:
SQL FUNCTION:
create function [dbo].[GetNumbersFromText](#String varchar(2000))
returns table as return
(
with C as
(
select cast(substring(S.Value, S1.Pos, S2.L) as int) as Number,
stuff(s.Value, 1, S1.Pos + S2.L, '') as Value
from (select #String+' ') as S(Value)
cross apply (select patindex('%[0-9]%', S.Value)) as S1(Pos)
cross apply (select patindex('%[^0-9]%', stuff(S.Value, 1, S1.Pos, ''))) as S2(L)
union all
select cast(substring(S.Value, S1.Pos, S2.L) as int),
stuff(S.Value, 1, S1.Pos + S2.L, '')
from C as S
cross apply (select patindex('%[0-9]%', S.Value)) as S1(Pos)
cross apply (select patindex('%[^0-9]%', stuff(S.Value, 1, S1.Pos, ''))) as S2(L)
where patindex('%[0-9]%', S.Value) > 0
)
select Number
from C
)
SELECT STATEMENT with SUB Query:
declare #S varchar(max)
select number from GetNumbersFromText(Select SomeColm From Table_Name) option (maxrecursion 0)
BTW, im using sql server 2005.
Thanks!
If the numeric part is always at the beginning, then you can use this:
PATINDEX('%[0-9][^0-9]%', ConcUnit)
to get the index of the last digit.
Thus, this:
DECLARE #str VARCHAR(MAX) = '4000 ug/ML'
SELECT LEFT(#str, PATINDEX('%[0-9][^0-9]%', #str )) AS Number,
LTRIM(RIGHT(#str, LEN(#str) - PATINDEX('%[0-9][^0-9]%', #str ))) As Unit
gives you:
Number Unit
-------------
4000 ug/ML
EDIT:
If numeric data include double values as well, then you can use this:
SELECT LEN(#str) - PATINDEX ('%[^0-9][0-9]%', REVERSE(#str))
to get the index of the last digit.
Thus, this:
SELECT LEFT(#str, LEN(#str) - PATINDEX ('%[^0-9][0-9]%', REVERSE(#str)))
gives you the numeric part.
And this:
SELECT LEFT(#str, LEN(#str) - PATINDEX ('%[^0-9][0-9]%', REVERSE(#str))) AS Numeric,
CASE
WHEN CHARINDEX ('%', #str) <> 0 THEN LTRIM(RIGHT(#str, LEN(#str) - CHARINDEX ('%', #str)))
ELSE LTRIM(RIGHT(#str, PATINDEX ('%[^0-9][0-9]%', REVERSE(#str))))
END AS Unit
gives you both numberic and unit part.
Here are some tests that I made with the data you have posted:
Input:
DECLARE #str VARCHAR(MAX) = '50 000ug/ML'
Output:
Numeric Unit
------------
50 000 ug/ML
Input:
DECLARE #str VARCHAR(MAX) = '99.5%'
Output:
Numeric Unit
------------
99.5
Input:
DECLARE #str VARCHAR(MAX) = '4000 . 35 % ug/ML'
Output:
Numeric Unit
------------------
4000 . 35 ug/ML
Here is my answer. Check output in SQLFiddle for the same.
create TABLE temp
(
string NVARCHAR(50)
)
INSERT INTO temp (string)
VALUES
('4000 ug\ml'),
('2000 ug\ml'),
('%'),
('ug\ml')
SELECT subsrtunit,LEFT(subsrtnumeric, PATINDEX('%[^0-9]%', subsrtnumeric+'t') - 1)
FROM (
SELECT subsrtunit = SUBSTRING(string, posofchar, LEN(string)),
subsrtnumeric = SUBSTRING(string, posofnumber, LEN(string))
FROM (
SELECT string, posofchar = PATINDEX('%[^0-9]%', string),
posofnumber = PATINDEX('%[0-9]%', string)
FROM temp
) d
) t
Updated Version to handle 99.5 ug\ml
create TABLE temp
(
string NVARCHAR(50)
)
INSERT INTO temp (string)
VALUES
('4000 ug\ml'),
('2000 ug\ml'),
('%'),
('ug\ml'),
('99.5 ug\ml')
SELECT subsrtunit,LEFT(subsrtnumeric, PATINDEX('%[^0-9.]%', subsrtnumeric+'t') - 1)
FROM (
SELECT subsrtunit = SUBSTRING(string, posofchar, LEN(string)),
subsrtnumeric = SUBSTRING(string, posofnumber, LEN(string))
FROM (
SELECT string, posofchar = PATINDEX('%[^0-9.]%', string),
posofnumber = PATINDEX('%[0-9.]%', string)
FROM temp
) d
) t
Updated Version: To handle 1 000 ug\ml,20 000ug\ml
create TABLE temp
(
string NVARCHAR(50)
)
INSERT INTO temp (string)
VALUES
('4000 ug\ml'),
('2000 ug\ml'),
('%'),
('ug\ml'),
('99.5 ug\ml'),
('1 000 ug\ml'),
('20 000ug\ml')
SELECT substring(replace(subsrtunit,' ',''),PATINDEX('%[0-9.]%', replace(subsrtunit,' ',''))+1,len(subsrtunit)),
LEFT(replace(subsrtnumeric,' ',''), PATINDEX('%[^0-9.]%', replace(subsrtnumeric,' ','')+'t') - 1)
FROM (
SELECT subsrtunit = SUBSTRING(string, posofchar, LEN(string)),
subsrtnumeric = SUBSTRING(string, posofnumber, LEN(string))
FROM (
SELECT string, posofchar = PATINDEX('%[^0-9.]%', replace(string,' ','')),
posofnumber = PATINDEX('%[0-9.]%', replace(string,' ',''))
FROM temp
) d
) t
Check out SQLFiddle for the same.
Would something like this work? Based on the shown data it looks like it would.
Apply it to your data set as a select and if you like the results then you can make an update from it.
WITH cte as (SELECT 'ug/mL' ConcUnit, 500 as [Numeric], '' as Unit
UNION ALL SELECT '2000 ug/mL', NULL, '')
SELECT
[ConcUnit] as [ConcUnit],
[Numeric] as [Original Numeric],
[Unit] as [Original Unit],
CASE WHEN ConcUnit LIKE '% %' THEN
SUBSTRING(ConcUnit, 1, CHARINDEX(' ', ConcUnit) - 1)
ELSE [Numeric] END as [New Numeric],
CASE WHEN ConcUnit LIKE '% %'
THEN SUBSTRING(ConcUnit, CHARINDEX(' ', ConcUnit) + 1, LEN(ConcUnit))
ELSE ConcUnit END as [New Unit]
FROM cte
change #concunit & #unitx Respectively
DECLARE #concunit varchar(10)='45.5%'
DECLARE #unitx varchar(10)='%'
BEGIN
SELECT RTRIM(SUBSTRING( #concunit , 1 , CHARINDEX( #unitx , #concunit
) - 1
)) AS Number,
RTRIM(SUBSTRING( #concunit , CHARINDEX( #unitx , #concunit
) , LEN( #concunit
) - (CHARINDEX( #unitx , #concunit
) - 1)
)) AS Unit
end
I had the same dilemma, but in my case the alpha's were in front of the numerics.
So using the logic that #Giorgos Betsos added to his answer, I just reversed it.
I.e., when your input is :
abc123
You can split it like this:
declare #input varchar(30) = 'abc123'
select
replace(#input,reverse(LEFT(reverse(#input), PATINDEX('%[0-9][^0-9]%', reverse(#input) ))),'') Alpha
, reverse(LEFT(reverse(#input), PATINDEX('%[0-9][^0-9]%', reverse(#input) ))) Numeric
Results :

Resources