GET particular value from split string result in sql - sql

I FIRE BELOVED QUERY
SELECT value
FROM STRING_SPLIT('3G-4RPE-L250-S80-27K-UNV-DIM-WT-RG1-CP-S(9)', '-')
I GOT FOLLOWING RESULT
VALUE
3G
4RPE
L250
S80
27K
UNV
DIM
WT
RG1
CP
S(9)
IS IT POSSIBLE TO GET PARTICULAR WORD LIKE 4RPE, RG1 FROM ABOVE RESULT SET IN SQL?

One option is with a bit of JSON. Here we convert your string into a JSON Array. Then it becomes a small matter to extract the values.
Example
Declare #S varchar(max) = '3G-4RPE-L250-S80-27K-UNV-DIM-WT-RG1-CP-S(9)'
Set #S = '["'+replace(string_escape(#S,'json'),'-','","')+'"]'
Select Pos1 = JSON_VALUE(#S,'$[1]')
,Pos8 = JSON_VALUE(#S,'$[8]')
Results
Pos1 Pos8
4RPE RG1
2nd Option
Select *
From OpenJSON(#S)
Where [key] in (1,8)
Results
key value type
1 4RPE 1
8 RG1 1

Related

Converting ID values in substring of varchar to it's lookup values

I have a SQL column of type varchar that is meant to contain SQL conditions, eg (3 rows below):
WHERE Language = 1 OR Region = 10
WHERE Color= 3 OR Region = 10
WHERE Status = 1 OR Region = 10 AND Language = 1
I need to create a query to get the lookup values of these that can be sent to any non technical person. The output would be:
WHERE Language = English OR Region = Canada
WHERE Color= Red OR Region = Canada
WHERE Status = Active OR Region = Canada AND Language = English
I know I can first put all the lookups in a temp table and then use the REPLACE function, but I was wondering if there's any better (and shorter) way to do this? Any help would be appriciated.
Thanks.
I would create subquery column values ready to replace originals, f.eks for Regions:
SELECT
CONCAT('%Region = ', Region,'%') ConditionToJoin,
CONCAT('Region = ', Region) ConditionToFind,
CONCAT('Region = ', RegionName) ConditionToReplace
FROM Regions
The join this sub query with condition rows using LIKE operator and ConditionToJoin column.
There is also a question if you need to handle situations like:
Region=1
Region =1
etc...
Alternatively you could write user function to wash data and perform all replacements, something like:
CREATE FUNCTION replaceLookups(#condition VARCHAR(MAX))
RETURNS VARCHAR(MAX)
BEGIN
#string_replacement VARCHAR(MAX), #string_pattern VARCHAR(MAX);
SET #string_pattern = SELECT TOP 1 CONCAT('Region = ', Region) FROM Regions WHERE #condition LIKE CONCAT('%Region = ', Region, '%')
SET #string_replacement = SELECT TOP 1 CONCAT('Region = ', RegionName) FROM Regions WHERE #condition LIKE CONCAT('%Region = ', Region, '%')
SET #ret = REPLACE(#condition, #string_pattern, #string_replacement)
... --and so on for each lookup
RETURN #ret
END
Word of warning. Above code was written from top of my head - might need some work. Also I wouldn't expect great performance.

MS-SQL - Extracting numerical portion of a string

I have an MS-SQL table, with a column titled 'ImportCount'.
Data in this column follows the below format:
ImportCount
[Schedules] 1376 schedule items imported from location H:\FOLDERA\AA\XX...
[Schedules] 10201 schedule items imported from location H:\FOLDERZZ\PERS\YY...
[Schedules] 999 schedule items imported from location R:\PERS\FOLDERA\AA\XX...
[Schedules] 21 schedule items imported from location H:\FOLDERA\MM\2014ZZ...
What I would like to do is extract that numerical portion of the data (which varies in length), but am struggling to get the right result. Would appreciate any help on this!
Thanks.
Try
select left(ImportCount, patindex('%[^0-9]%', ImportCount+'.') - 1)
select SUBSTRING(ImportCount,13,patindex('% schedule items%',ImportCount)-13) from table name
Try this..You can declare it as a SQL function also.
DECLARE #intText INT
DECLARE #textAplhaNumeric varchar(100)
set #textAplhaNumeric = '1376 schedule items imported from location'
SET #intText = PATINDEX('%[^0-9]%', #textAplhaNumeric)
BEGIN
WHILE #intText > 0
BEGIN
SET #textAplhaNumeric = STUFF(#textAplhaNumeric, #intText, 1, '' )
SET #intText = PATINDEX('%[^0-9]%', #textAplhaNumeric)
END
END
Select #textAplhaNumeric //output is 1376
It will work in case of NULL or empty values.
Please try:
SELECT LEFT(Val,PATINDEX('%[^0-9]%', Val+'a')-1) from(
SELECT
STUFF(ImportCount, 1, PATINDEX('%[0-9]%', ImportCount)-1, '') Val
FROM YourTable
)x

Turning an XML into a select

I'm trying to turn this XML string into a select
I have #Schedule XML = '<days><day enabled="0">0</day><day enabled="1">1</day><day enabled="1">2</day><day enabled="1">3</day><day enabled="1">4</day><day enabled="1">5</day><day enabled="0">6</day></days>'
What I'm trying to see at the end is..
DayNumber DayEnabled
0 0
1 1
2 1
3 1
4 1
5 1
6 0
I've tried a few ways, so far nothing is working right.. I am handling this as an XML data type, I'd prefer not to use a function as this will just be in a stored procedure..
Update: Maybe I didn't explain it correctly..
I have a stored procedure, XML is one of the parameters passed to it, I need to send it to a table to be inserted, so I'm trying to do the following..
INSERT INTO tblDays (DayNumber, DayEnabled)
SELECT #XMLParsedOrTempTableWithResults
I just can't figure out how to parsed the parameter
DECLARE #myXML as XML = '<days><day enabled="0">0</day><day enabled="1">1</day><day enabled="1">2</day><day enabled="1">3</day><day enabled="1">4</day><day enabled="1">5</day><day enabled="0">6</day></days>'
DECLARE #XMLDataTable table
(
DayNumber int
,DayEnabled int
)
INSERT INTO #XMLDataTable
SELECT d.value('text()[1]','int') AS [DayNumber]
,d.value('(#enabled)[1]','int') AS [DayEnabled]
FROM #myXML.nodes('/days/*') ds(d)
SELECT * FROM #XMLDataTable
Refer:
http://beyondrelational.com/modules/2/blogs/28/posts/10279/xquery-labs-a-collection-of-xquery-sample-scripts.aspx
The XMLTABLE function is how most XML-enabled DBMSes shred an XML document into a relational result set.
This example uses DB2's syntax for XMLTABLE and an input parameter passed into a stored procedure:
INSERT INTO tblDays (DayNumber, DayEnabled)
SELECT X.* FROM
XMLTABLE ('$d/days/day' PASSING XMLPARSE( DOCUMENT SPinputParm ) as "d"
COLUMNS
dayNumber INTEGER PATH '.',
dayEnabled SMALLINT PATH '#enabled'
) AS X
;

Return all results of substring with in string

I have some odd data in a vendor database but need to be able to extract multiple different parameters from one field in the db.
So from this example i would like to pull out all items that fall between (" % ")
Between quotes is a string, disregard that it looks like code:
"Func_GetParameterLatestValue("IBW Patient Height RT Assess") kHeight =Func_GetParameterLatestValue("Height For IBW Vent Misc") If (kSex) = "" Then
Return_Value =NULL Else If kHeight > 0 Then If kSex=1 Then Return_Value= Round(((kHeight - 152.4)*.91)+50,0) Else
Return_Value= Round(((kHeight - 152.4)*.91)+45.5,0) End IF Else Return_Value = NULL End IF End IF ' Return_Value = kHeight '("IBW Patient Height RT Assess")"
so the return values would be:
IBW Patient Height RT Assess,
Height For IBW Vent Misc,
IBW Patient Height RT Assess
Im open to any suggestions to try and make this work. Ideally i would like to be able to slam the results in a subquery as well to make sure that they exist on another table.
This query currently returns the first instance
select vbs.Name,
SUBSTRING(sd.FormulaDetails,
CHARINDEX('("', sd.FormulaDetails)+2,(CHARINDEX('")',sd.FormulaDetails) - CHARINDEX('("', sd.FormulaDetails))-2)
from StatementDefinitions sd, MvVBScript vbs
where sd.ScriptID = vbs.ID
You can do this recursively with a WITH statement. Here's a shot at it. Change varchar(max) to whatever the data type of your FormulaDetails column is. In case you want it, this query returns the ScriptID and numbers the position of the chunk it finds (so 'Height For IBW Vent Misc' would be occurrence 2)
with Chunks(id,occurrence,position,token,remainder) as (
select
ScriptID,
cast(0 as int),
charindex(#token,FormulaDetails),
cast('' as varchar(max)),
substring(c,charindex(#token,FormulaDetails)+1,len(FormulaDetails))
from StatementDefinitions
where FormulaDetails like '%'+#token+'%'
union all
select
id,
occurrence+1,
charindex(#token,remainder)+position,
cast(substring(remainder,1,charindex(#token,remainder)-1) as varchar(max)),
substring(remainder,charindex(#token,remainder)+1,len(remainder))
from Chunks
where remainder like '%'+#token+'%'
)
select id, occurrence, token from Chunks
where occurrence > 0
order by id;

Stored procedure to find next and previous row in SQL Server 2005

Right now I have this code to find next and previous rows using SQL Server 2005. intID is the gallery id number using bigint data type:
SQL = "SELECT TOP 1 max(p.galleryID) as previousrec, min(n.galleryID) AS nextrec FROM gallery AS p CROSS JOIN gallery AS n where p.galleryid < '"&intID&"' and n.galleryid > '"&intID&"'"
Set rsRec = Server.CreateObject("ADODB.Recordset")
rsRec.Open sql, Conn
strNext = rsRec("nextrec")
strPrevious = rsRec("previousrec")
rsRec.close
set rsRec = nothing
Problem Number 1:
The newest row will return nulls on the 'next record' because there is none. The oldest row will return nulls because there isn't a 'previous record'. So if either the 'next record' or 'previous record' doesn't exist then it returns nulls for both.
Problem Number 2:
I want to create a stored procedure to call from the DB so intid can just be passed to it
TIA
This will yield NULL for previous on the first row, and NULL for next on the last row. Though your ordering seems backwards to me; why is "next" lower than "previous"?
CREATE PROCEDURE dbo.GetGalleryBookends
#GalleryID INT
AS
BEGIN
SET NOCOUNT ON;
;WITH n AS
(
SELECT galleryID, rn = ROW_NUMBER()
OVER (ORDER BY galleryID)
FROM dbo.gallery
)
SELECT
previousrec = MAX(nA.galleryID),
nextrec = MIN(nB.galleryID)
FROM n
LEFT OUTER JOIN n AS nA
ON nA.rn = n.rn - 1
LEFT OUTER JOIN n AS nB
ON nB.rn = n.rn + 1
WHERE n.galleryID = #galleryID;
END
GO
Also, it doesn't make sense to want an empty string instead of NULL. Your ASP code can deal with NULL values just fine, otherwise you'd have to convert the resulting integers to strings every time. If you really want this you can say:
previousrec = COALESCE(CONVERT(VARCHAR(12), MIN(nA.galleryID)), ''),
nextrec = COALESCE(CONVERT(VARCHAR(12), MAX(nB.galleryID)), '')
But this will no longer work well when you move from ASP to ASP.NET because types are much more explicit. Much better to just have the application code be able to deal with, instead of being afraid of, NULL values.
This seems like a lot of work to get the previous and next ID, without retrieving any information about the current ID. Are you implementing paging? If so I highly recommend reviewing this article and this follow-up conversation.
Try this (nb not tested)
SELECT TOP 1 max(p.galleryID) as previousrec, min(n.galleryID) AS nextrec
FROM gallery AS p
CROSS JOIN gallery AS n
where (p.galleryid < #intID or p.galleryid is null)
and (n.galleryid > #intID or n.galleryid is null)
I'm assuming you validate that intID is an integer before using this code.
As for a stored procedure -- are you asking how to write a stored procedure? If so there are many tutorials which are quite good on the web.
Since Hogan contributed with the SQL statement, let me contribute with the stored proc part:
CREATE PROCEDURE spGetNextAndPreviousRecords
-- Add the parameters for the stored procedure here
#intID int
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
SELECT TOP 1 max(p.galleryID) as previousrec, min(n.galleryID) AS nextrec
FROM gallery AS p
CROSS JOIN gallery AS n
where (p.galleryid < #intID or p.galleryid is null)
and (n.galleryid > #intID or n.galleryid is null)
END
And you call this from code as follows (assuming VB.NET):
Using c As New SqlConnection(ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString)
c.Open()
Dim command = New SqlCommand("spGetNextAndPreviousRecords")
command.Parameters.AddWithValue("#intID", yourID)
Dim reader as SqlDataReader = command.ExecuteReader()
While(reader.Read())
' read the result here
End While
End Using