Select a specific number from a row in sql query - sql

I want to select a SQL Query for only "09xxxxxxxxx" from below table :
021-77083709 - 09125800327
09123301673 22514057
09121964217 09332712035
Its might be anywhere in the row and I want to select these numbers. This mean "09" + 9 character after that.
For Example in overhead rows, select these numbers :
09125800327
09123301673
09121964217
09332712035
My Table
http://upload.tehran98.com/upme/uploads/33a59e81d6d51d311.jpg
Thanks

This will get you part of the way there...
SELECT SUBSTRING(tbl.columnName,
PATINDEX('%09[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]%',
tbl.ColumnName), 11) FirstOccurrance
FROM TableName tbl
WHERE tbl.columnName LIKE '%09[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]%'
This will only extract the first occurrence of the pattern within a column,
also the pattern matching is pretty limited.
By the way in your example is 09 + 9 characters not 10
Here is a function that can be used to extract all matching values in a column as a csv string
CREATE FUNCTION dbo.FilterValues
(
#OriginalValue NVARCHAR(2000)
)
RETURNS NVARCHAR(2000)
AS
BEGIN
DECLARE #IDX INT = PATINDEX('%09[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]%',
#OriginalValue);
DECLARE #Temp NVARCHAR(4000) = #OriginalValue;
DECLARE #Result NVARCHAR(4000) = '';
WHILE ( #IDX IS NOT NULL
AND #IDX > 0
)
BEGIN
SET #Result = #Result + SUBSTRING(#Temp, #IDX, 11);
SET #Temp = SUBSTRING(#Temp, #IDX + 11, LEN(#Temp) - 11);
SET #IDX = PATINDEX('%09[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]%',
#Temp);
IF ( #IDX IS NOT NULL
AND #IDX > 0
)
BEGIN
SET #Result = #Result + ',';
END
END
RETURN #Result;
END
Here is an example on how to use the query with the function
SELECT dbo.FilterValues(tbl.ColumnName) MatchedValues
FROM TableName tbl
WHERE tbl.columnName LIKE '%09[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]%'

Related

Query stuff result left join on multiple ids [duplicate]

Duplicate of
Dynamic SQL Comma Delimited Value Query
Parameterized Queries with Like and In
I have a SQL Server Stored Procedure where I would like to pass a varchar full of comma delimited values to an IN function. For example:
DECLARE #Ids varchar(50);
SET #Ids = '1,2,3,5,4,6,7,98,234';
SELECT *
FROM sometable
WHERE tableid IN (#Ids);
This does not work of course. I get the error:
Conversion failed when converting the varchar value '1,2,3,5,4,6,7,98,234' to data type int.
How can I accomplish this (or something relatively similar) without resorting to building dynamic SQL?
Of course if you're lazy like me, you could just do this:
Declare #Ids varchar(50) Set #Ids = ',1,2,3,5,4,6,7,98,234,'
Select * from sometable
where Charindex(','+cast(tableid as varchar(8000))+',', #Ids) > 0
Don't use a function that loops to split a string!, my function below will split a string very fast, with no looping!
Before you use my function, you need to set up a "helper" table, you only need to do this one time per database:
CREATE TABLE Numbers
(Number int NOT NULL,
CONSTRAINT PK_Numbers PRIMARY KEY CLUSTERED (Number ASC)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
DECLARE #x int
SET #x=0
WHILE #x<8000
BEGIN
SET #x=#x+1
INSERT INTO Numbers VALUES (#x)
END
use this function to split your string, which does not loop and is very fast:
CREATE FUNCTION [dbo].[FN_ListToTable]
(
#SplitOn char(1) --REQUIRED, the character to split the #List string on
,#List varchar(8000) --REQUIRED, the list to split apart
)
RETURNS
#ParsedList table
(
ListValue varchar(500)
)
AS
BEGIN
/**
Takes the given #List string and splits it apart based on the given #SplitOn character.
A table is returned, one row per split item, with a column name "ListValue".
This function workes for fixed or variable lenght items.
Empty and null items will not be included in the results set.
Returns a table, one row per item in the list, with a column name "ListValue"
EXAMPLE:
----------
SELECT * FROM dbo.FN_ListToTable(',','1,12,123,1234,54321,6,A,*,|||,,,,B')
returns:
ListValue
-----------
1
12
123
1234
54321
6
A
*
|||
B
(10 row(s) affected)
**/
----------------
--SINGLE QUERY-- --this will not return empty rows
----------------
INSERT INTO #ParsedList
(ListValue)
SELECT
ListValue
FROM (SELECT
LTRIM(RTRIM(SUBSTRING(List2, number+1, CHARINDEX(#SplitOn, List2, number+1)-number - 1))) AS ListValue
FROM (
SELECT #SplitOn + #List + #SplitOn AS List2
) AS dt
INNER JOIN Numbers n ON n.Number < LEN(dt.List2)
WHERE SUBSTRING(List2, number, 1) = #SplitOn
) dt2
WHERE ListValue IS NOT NULL AND ListValue!=''
RETURN
END --Function FN_ListToTable
you can use this function as a table in a join:
SELECT
Col1, COl2, Col3...
FROM YourTable
INNER JOIN FN_ListToTable(',',#YourString) s ON YourTable.ID = s.ListValue
Here is your example:
Select * from sometable where tableid in(SELECT ListValue FROM dbo.FN_ListToTable(',',#Ids) s)
No Table No Function No Loop
Building on the idea of parsing your list into a table our DBA suggested using XML.
Declare #Ids varchar(50)
Set #Ids = ‘1,2,3,5,4,6,7,98,234’
DECLARE #XML XML
SET #XML = CAST('<i>' + REPLACE(#Ids, ',', '</i><i>') + '</i>' AS XML)
SELECT *
FROM
SomeTable
INNER JOIN #XML.nodes('i') x(i)
ON SomeTable .Id = x.i.value('.', 'VARCHAR(MAX)')
These seems to have the same performance as #KM's answer but, I think, a lot simpler.
You can create a function that returns a table.
so your statement would be something like
select * from someable
join Splitfunction(#ids) as splits on sometable.id = splits.id
Here is a simular function.
CREATE FUNCTION [dbo].[FUNC_SplitOrderIDs]
(
#OrderList varchar(500)
)
RETURNS
#ParsedList table
(
OrderID int
)
AS
BEGIN
DECLARE #OrderID varchar(10), #Pos int
SET #OrderList = LTRIM(RTRIM(#OrderList))+ ','
SET #Pos = CHARINDEX(',', #OrderList, 1)
IF REPLACE(#OrderList, ',', '') <> ''
BEGIN
WHILE #Pos > 0
BEGIN
SET #OrderID = LTRIM(RTRIM(LEFT(#OrderList, #Pos - 1)))
IF #OrderID <> ''
BEGIN
INSERT INTO #ParsedList (OrderID)
VALUES (CAST(#OrderID AS int)) --Use Appropriate conversion
END
SET #OrderList = RIGHT(#OrderList, LEN(#OrderList) - #Pos)
SET #Pos = CHARINDEX(',', #OrderList, 1)
END
END
RETURN
END
It's a very common question. Canned answer, several nice techniques:
http://www.sommarskog.se/arrays-in-sql-2005.html
This works perfectly! The below answers are too complicated. Don't look at this as dynamic. Set up your store procedure as follows:
(#id as varchar(50))
as
Declare #query as nvarchar(max)
set #query ='
select * from table
where id in('+#id+')'
EXECUTE sp_executesql #query
I can suggest using WITH like this:
DECLARE #Delim char(1) = ',';
SET #Ids = #Ids + #Delim;
WITH CTE(i, ls, id) AS (
SELECT 1, CHARINDEX(#Delim, #Ids, 1), SUBSTRING(#Ids, 1, CHARINDEX(#Delim, #Ids, 1) - 1)
UNION ALL
SELECT i + 1, CHARINDEX(#Delim, #Ids, ls + 1), SUBSTRING(#Ids, ls + 1, CHARINDEX(#Delim, #Ids, ls + 1) - CHARINDEX(#Delim, #Ids, ls) - 1)
FROM CTE
WHERE CHARINDEX(#Delim, #Ids, ls + 1) > 1
)
SELECT t.*
FROM yourTable t
INNER JOIN
CTE c
ON t.id = c.id;
I think a very simple solution could be following:
DECLARE #Ids varchar(50);
SET #Ids = '1,2,3,5,4,6,7,98,234';
SELECT *
FROM sometable
WHERE ','+#Ids+',' LIKE '%,'+CONVERT(VARCHAR(50),tableid)+',%';
Without using dynamic SQL, you have to take the input variable and use a split function to put the data into a temp table and then join to that.
Thanks, for your function I Used IT........................
This is my EXAMPLE
**UPDATE [RD].[PurchaseOrderHeader]
SET [DispatchCycleNumber] ='10'
WHERE OrderNumber in(select * FROM XA.fn_SplitOrderIDs(#InvoiceNumberList))**
CREATE FUNCTION [XA].[fn_SplitOrderIDs]
(
#OrderList varchar(500)
)
RETURNS
#ParsedList table
(
OrderID int
)
AS
BEGIN
DECLARE #OrderID varchar(10), #Pos int
SET #OrderList = LTRIM(RTRIM(#OrderList))+ ','
SET #Pos = CHARINDEX(',', #OrderList, 1)
IF REPLACE(#OrderList, ',', '') <> ''
BEGIN
WHILE #Pos > 0
BEGIN
SET #OrderID = LTRIM(RTRIM(LEFT(#OrderList, #Pos - 1)))
IF #OrderID <> ''
BEGIN
INSERT INTO #ParsedList (OrderID)
VALUES (CAST(#OrderID AS int)) --Use Appropriate conversion
END
SET #OrderList = RIGHT(#OrderList, LEN(#OrderList) - #Pos)
SET #Pos = CHARINDEX(',', #OrderList, 1)
END
END
RETURN
END
If you use SQL Server 2008 or higher, use table valued parameters; for example:
CREATE PROCEDURE [dbo].[GetAccounts](#accountIds nvarchar)
AS
BEGIN
SELECT *
FROM accountsTable
WHERE accountId IN (select * from #accountIds)
END
CREATE TYPE intListTableType AS TABLE (n int NOT NULL)
DECLARE #tvp intListTableType
-- inserts each id to one row in the tvp table
INSERT #tvp(n) VALUES (16509),(16685),(46173),(42925),(46167),(5511)
EXEC GetAccounts #tvp
Its been a while but I have done this in the past using XML as a interim.
I can't take any credit for this, but I'm afraid I no longer know where I got this idea from:
-- declare the variables needed
DECLARE #xml as xml,#str as varchar(100),#delimiter as varchar(10)
-- The string you want to split
SET #str='A,B,C,D,E,Bert,Ernie,1,2,3,4,5'
-- What you want to split on. Can be a single character or a string
SET #delimiter =','
-- Convert it to an XML document
SET #xml = cast(('<X>'+replace(#str,#delimiter ,'</X><X>')+'</X>') as xml)
-- Select back from the XML
SELECT N.value('.', 'varchar(10)') as value FROM #xml.nodes('X') as T(N)
Create a table function like below which parse comma separated varchar and returns a table that can be inner joined with other tables.
CREATE FUNCTION [dbo].[fn_SplitList]
(
#inString varchar(MAX) = '',
#inDelimiter char(1) = ',' -- Keep the delimiter to 100 chars or less. Generally a delimiter will be 1-2 chars only.
)
RETURNS #tbl_Return table
(
Unit varchar(1000) COLLATE Latin1_General_BIN
)
AS
BEGIN
INSERT INTO #tbl_Return
SELECT DISTINCT
LTRIM(RTRIM(piece.value('./text()[1]', 'varchar(1000)'))) COLLATE DATABASE_DEFAULT AS Unit
FROM
(
--
-- Replace any delimiters in the string with the "X" tag.
--
SELECT
CAST(('<X>' + REPLACE(s0.prsString, s0.prsSplitDelimit, '</X><X>') + '</X>') AS xml).query('.') AS units
FROM
(
--
-- Convert the string and delimiter into XML.
--
SELECT
(SELECT #inString FOR XML PATH('')) AS prsString,
(SELECT #inDelimiter FOR XML PATH('')) AS prsSplitDelimit
) AS s0
) AS s1
CROSS APPLY units.nodes('X') x(piece)
RETURN
END
=================================================
Now consume above created table function in your code,creation of function is one time activity in your database that can be used across databases as well on same server.
DECLARE #Ids varchar(50);
SET #Ids = '1,2,3,5,4,6,7,98,234';
SELECT
*
FROM sometable AS st
INNER JOIN fn_SplitList(#ids, ',') AS sl
ON sl.unit = st.tableid
I've written a stored procedure to show how to do this before.
You basically have to process the string.
I tried to post the code here but the formatting got all screwy.
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[uspSplitTextList]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[uspSplitTextList]
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS ON
GO
/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
-- uspSplitTextList
--
-- Description:
-- splits a separated list of text items and returns the text items
--
-- Arguments:
-- #list_text - list of text items
-- #Delimiter - delimiter
--
-- Notes:
-- 02/22/2006 - WSR : use DATALENGTH instead of LEN throughout because LEN doesn't count trailing blanks
--
-- History:
-- 02/22/2006 - WSR : revised algorithm to account for items crossing 8000 character boundary
-- 09/18/2006 - WSR : added to this project
--
CREATE PROCEDURE uspSplitTextList
#list_text text,
#Delimiter varchar(3)
AS
SET NOCOUNT ON
DECLARE #InputLen integer -- input text length
DECLARE #TextPos integer -- current position within input text
DECLARE #Chunk varchar(8000) -- chunk within input text
DECLARE #ChunkPos integer -- current position within chunk
DECLARE #DelimPos integer -- position of delimiter
DECLARE #ChunkLen integer -- chunk length
DECLARE #DelimLen integer -- delimiter length
DECLARE #ItemBegPos integer -- item starting position in text
DECLARE #ItemOrder integer -- item order in list
DECLARE #DelimChar varchar(1) -- first character of delimiter (simple delimiter)
-- create table to hold list items
-- actually their positions because we may want to scrub this list eliminating bad entries before substring is applied
CREATE TABLE #list_items ( item_order integer, item_begpos integer, item_endpos integer )
-- process list
IF #list_text IS NOT NULL
BEGIN
-- initialize
SET #InputLen = DATALENGTH(#list_text)
SET #TextPos = 1
SET #DelimChar = SUBSTRING(#Delimiter, 1, 1)
SET #DelimLen = DATALENGTH(#Delimiter)
SET #ItemBegPos = 1
SET #ItemOrder = 1
SET #ChunkLen = 1
-- cycle through input processing chunks
WHILE #TextPos <= #InputLen AND #ChunkLen <> 0
BEGIN
-- get current chunk
SET #Chunk = SUBSTRING(#list_text, #TextPos, 8000)
-- setup initial variable values
SET #ChunkPos = 1
SET #ChunkLen = DATALENGTH(#Chunk)
SET #DelimPos = CHARINDEX(#DelimChar, #Chunk, #ChunkPos)
-- loop over the chunk, until the last delimiter
WHILE #ChunkPos <= #ChunkLen AND #DelimPos <> 0
BEGIN
-- see if this is a full delimiter
IF SUBSTRING(#list_text, (#TextPos + #DelimPos - 1), #DelimLen) = #Delimiter
BEGIN
-- insert position
INSERT INTO #list_items (item_order, item_begpos, item_endpos)
VALUES (#ItemOrder, #ItemBegPos, (#TextPos + #DelimPos - 1) - 1)
-- adjust positions
SET #ItemOrder = #ItemOrder + 1
SET #ItemBegPos = (#TextPos + #DelimPos - 1) + #DelimLen
SET #ChunkPos = #DelimPos + #DelimLen
END
ELSE
BEGIN
-- adjust positions
SET #ChunkPos = #DelimPos + 1
END
-- find next delimiter
SET #DelimPos = CHARINDEX(#DelimChar, #Chunk, #ChunkPos)
END
-- adjust positions
SET #TextPos = #TextPos + #ChunkLen
END
-- handle last item
IF #ItemBegPos <= #InputLen
BEGIN
-- insert position
INSERT INTO #list_items (item_order, item_begpos, item_endpos)
VALUES (#ItemOrder, #ItemBegPos, #InputLen)
END
-- delete the bad items
DELETE FROM #list_items
WHERE item_endpos < item_begpos
-- return list items
SELECT SUBSTRING(#list_text, item_begpos, (item_endpos - item_begpos + 1)) AS item_text, item_order, item_begpos, item_endpos
FROM #list_items
ORDER BY item_order
END
DROP TABLE #list_items
RETURN
/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
I have same idea with user KM. but do not need extra table Number. Just this function only.
CREATE FUNCTION [dbo].[FN_ListToTable]
(
#SplitOn char(1) --REQUIRED, the character to split the #List string on
,#List varchar(8000) --REQUIRED, the list to split apart
)
RETURNS
#ParsedList table
(
ListValue varchar(500)
)
AS
BEGIN
DECLARE #number int = 0
DECLARE #childString varchar(502) = ''
DECLARE #lengthChildString int = 0
DECLARE #processString varchar(502) = #SplitOn + #List + #SplitOn
WHILE #number < LEN(#processString)
BEGIN
SET #number = #number + 1
SET #lengthChildString = CHARINDEX(#SplitOn, #processString, #number + 1) - #number - 1
IF #lengthChildString > 0
BEGIN
SET #childString = LTRIM(RTRIM(SUBSTRING(#processString, #number + 1, #lengthChildString)))
IF #childString IS NOT NULL AND #childString != ''
BEGIN
INSERT INTO #ParsedList(ListValue) VALUES (#childString)
SET #number = #number + #lengthChildString - 1
END
END
END
RETURN
END
And here is the test:
SELECT ListValue FROM dbo.FN_ListToTable('/','a/////bb/c')
Result:
ListValue
______________________
a
bb
c
-- select * from dbo.Split_ID('77,106')
ALTER FUNCTION dbo.Split_ID(#String varchar(8000))
returns #temptable TABLE (ID varchar(8000))
as
begin
declare #idx int
declare #slice varchar(8000)
declare #Delimiter char(1)
set #Delimiter =','
select #idx = 1
if len(#String)<1 or #String is null return
while #idx!= 0
begin
set #idx = charindex(#Delimiter,#String)
if #idx!=0
set #slice = left(#String,#idx - 1)
else
set #slice = #String
if(len(#slice)>0)
insert into #temptable(ID) values(#slice)
set #String = right(#String,len(#String) - #idx)
if len(#String) = 0 break
end
return
end
You could do it like this:
create or replace
PROCEDURE UDP_SETBOOKMARK
(
P_USERID IN VARCHAR2
, P_BOOKMARK IN VARCHAR2
) AS
BEGIN
UPDATE T_ER_Bewertung
SET LESEZEICHEN = P_BOOKMARK
WHERE STAMM_ID in( select regexp_substr(P_USERID,'[^,]+', 1, level) from dual
connect by regexp_substr(P_USERID, '[^,]+', 1, level) is not null )
and ER_ID = (select max(ER_ID) from T_ER_Bewertung_Kopie);
commit;
END UDP_SETBOOKMARK;
Then try it with
Begin
UDP_SETBOOKMARK ('1,2,3,4,5', 'Test');
End;
You can use this IN-Clause with regexp_substr in other situations too, just try it.
Error 493: The column 'i' that was returned from the nodes() method cannot be
used directly. It can only be used with one of the four XML data type
methods, exist(), nodes(), query(), and value(), or in IS NULL and IS NOT
NULL checks.
The above errorr was fixed in SQL Server 2014 by using following snippet
Declare #Ids varchar(50)
Set #Ids = '1,2,3,5,4,6,7,98,234'
DECLARE #XML XML
SET #XML = CAST('<i>' + REPLACE(#Ids, ',', '</i><i>') + '</i>' AS XML)
SELECT SomeTable.*
FROM
SomeTable
cross apply #XML.nodes('i') x(i)
where SomeTable .Id = x.i.value('.', 'VARCHAR(MAX)')
Try this:
SELECT ProductId, Name, Tags
FROM Product
WHERE '1,2,3,' LIKE '%' + CAST(ProductId AS VARCHAR(20)) + ',%';
As said on the last example of this link
Tons of answers here, but to add my two cents I think STRING_SPLIT is a very simple approach to this sort of problem:
DECLARE #Ids varchar(50);
SET #Ids = '1,2,3,5,4,6,7,98,234';
SELECT *
FROM sometable
WHERE tableid IN;
(SELECT value FROM STRING_SPLIT(#Ids, ','))
Best and simple approach.
DECLARE #AccumulateKeywordCopy NVARCHAR(2000),#IDDupCopy NVARCHAR(50);
SET #AccumulateKeywordCopy ='';
SET #IDDupCopy ='';
SET #IDDup = (SELECT CONVERT(VARCHAR(MAX), <columnName>) FROM <tableName> WHERE <clause>)
SET #AccumulateKeywordCopy = ','+#AccumulateKeyword+',';
SET #IDDupCopy = ','+#IDDup +',';
SET #IDDupCheck = CHARINDEX(#IDDupCopy,#AccumulateKeywordCopy)
CREATE TABLE t
(
id INT,
col1 VARCHAR(50)
)
INSERT INTO t
VALUES (1,
'param1')
INSERT INTO t
VALUES (2,
'param2')
INSERT INTO t
VALUES (3,
'param3')
INSERT INTO t
VALUES (4,
'param4')
INSERT INTO t
VALUES (5,
'param5')
DECLARE #params VARCHAR(100)
SET #params = ',param1,param2,param3,'
SELECT *
FROM t
WHERE Charindex(',' + Cast(col1 AS VARCHAR(8000)) + ',', #params) > 0
working fiddle find here Fiddle
I ran into the same issue, and I don't want to have any footprint on the source database - i.e. no stored procedures or functions. I went about it this way:
declare #IDs table (Value int)
insert into #IDs values(1)
insert into #IDs values(2)
insert into #IDs values(3)
insert into #IDs values(5)
insert into #IDs values(4)
insert into #IDs values(6)
insert into #IDs values(7)
insert into #IDs values(98)
insert into #IDs values(234)
SELECT *
FROM sometable
WHERE tableid IN (select Value from #IDs)
The answer by #RBarryYoung (above) worked for me.
But when you have spaces in between the comma separated string values, then it will omit IDs with spaces. So I removed the spaces.
Take a look at the code snippet below.
Declare #Ids varchar(50) Set #Ids = '1 , 2,3'
set #Ids=','+Replace(#Ids,' ', '')+',';
Select * from [tblEmployee]
where Charindex(','+cast(ID as varchar(8000))+',', #Ids) > 0
WHERE someId IN (SELECT convert(int, value) FROM string_split(#stringOfCommaDelimitedIds, ','))
The simplest way i found was to use FIND_IN_SET
FIND_IN_SET(column_name, values)
values=(1,2,3)
SELECT name WHERE FIND_IN_SET(id, values)
This came in handy for one of my requirements where I did not want to use CTE and also did not want to go with the inner join.
DECLARE #Ids varchar(50);
SET #Ids = '1,2,3,5,4,6,7,98,234';
SELECT
cn1,cn2,cn3
FROM tableName
WHERE columnName in (select Value from fn_SplitString(#ids, ','))
Function for split string :
CREATE FUNCTION [dbo].[fn_SplitString] ( #stringToSplit VARCHAR(MAX), #seperator Char )
RETURNS
#returnList TABLE ([Value] [nvarchar] (500))
AS
BEGIN
DECLARE #name NVARCHAR(255)
DECLARE #pos INT
WHILE CHARINDEX(#seperator, #stringToSplit) > 0
BEGIN
SELECT #pos = CHARINDEX(#seperator, #stringToSplit)
SELECT #name = SUBSTRING(#stringToSplit, 1, #pos-1)
INSERT INTO #returnList
SELECT #name
SELECT #stringToSplit = SUBSTRING(#stringToSplit, #pos+1, LEN(#stringToSplit)-#pos)
END
INSERT INTO #returnList
SELECT #stringToSplit
RETURN
END

Extract largest number from a string in T-SQL

I am importing working with data imported from excel files. There is a column with a string that can contain multiple numbers. I am trying to extract the largest number in the string or a 0 if there is no string.
The strings are in formats similar to:
"100% post-consumer recycled paper, 50% post-consumer recycled cover, 90% post-consumer recycled wire."
"Paper contains 30% post-consumer content."
or sometimes a empty string or null.
Given the irregular formatting of the string I am having trouble and any help would be appreciated.
Here's a scalar function that will take a string as an input and return the largest whole number it finds (up to a maximum of 3 digits, but from your question I've assumed you're dealing with percentages. If you need more digits, repeat the IF statements ad infinitum).
Paste this into SSMS and run it to create the function. To call it, do something like:
SELECT dbo.GetLargestNumberFromString(MyStringField) as [Largest Number in String]
FROM MyMessedUpData
Function:
CREATE FUNCTION GetLargestNumberFromString
(
#s varchar(max)
)
RETURNS int
AS
BEGIN
DECLARE #LargestNumber int, #i int
SET #i = 1
SET #LargestNumber = 0
WHILE #i <= LEN(#s)
BEGIN
IF SUBSTRING(#s, #i, 3) like '[0-9][0-9][0-9]'
BEGIN
IF CAST(SUBSTRING(#s, #i,3) as int) > #LargestNumber OR #LargestNumber IS NULL
SET #LargestNumber = CAST(SUBSTRING(#s, #i,3) as int);
END
IF SUBSTRING(#s, #i, 2) like '[0-9][0-9]'
BEGIN
IF CAST(SUBSTRING(#s, #i,2) as int) > #LargestNumber OR #LargestNumber IS NULL
SET #LargestNumber = CAST(SUBSTRING(#s, #i,2) as int);
END
IF SUBSTRING(#s, #i, 1) like '[0-9]' OR #LargestNumber IS NULL
BEGIN
IF CAST(SUBSTRING(#s, #i,1) as int) > #LargestNumber
SET #LargestNumber = CAST(SUBSTRING(#s, #i,1) as int);
END
SET #i = #i + 1
CONTINUE
END
RETURN #LargestNumber
END
Pull the data into SQL as-is
Write a query to get a distinct list of options in that column
Add a new column to store the desired value
Write an update statement to populate the new column
As far as determining the largest size, I think you need to look at your data set first, but the update could be as simple as:
DECLARE #COUNTER INT=1000
While EXISTS (SELECT * FROM <Table> WHERE NewColumn is NULL) AND #COUNTER>=0
BEGIN
UPDATE <Table> SET NewColumn=#COUNTER WHERE <SearchColumn> LIKE '%' + CONVERT(VARCHAR,#COUNTER) + '%' AND NewColumn is NULL
SET #COUNTER=#COUNTER-1
END
SQL Fiddle Demo
Generate the LEN(txt) possible RIGHT() fragments of txt. Trim each fragment at the first non-digit character. Test if the remainder is an int. Return the MAX().
SELECT
txt
,MAX(TRY_CONVERT(int,LEFT(RIGHT(txt,i),PATINDEX('%[^0-9]%',RIGHT(txt,i)+' ')-1)))
FROM MyTable
CROSS APPLY (
SELECT TOP(LEN(txt)) ROW_NUMBER() OVER(ORDER BY (SELECT NULL)) i FROM master.dbo.spt_values a, master.dbo.spt_values b
) x
GROUP BY txt
I ended up creating a function that handled it. Here is the code:
CREATE FUNCTION [dbo].[cal_GetMaxPercentFromString]
RETURNS float
AS
BEGIN
declare #Numbers Table(number float)
insert into #Numbers
Select 0
declare #temp as varchar(2000) = #string
declare #position int, #length int, #offset int
WHILE CHARINDEX('%', #temp) > 0
BEGIN
set #position = CHARINDEX('%', #temp)
set #offset = 1
set #length = -1
WHILE #position - #offset > 0 and #length < 0
BEGIN
if SUBSTRING(#temp, #position - #offset, 1) not LIKE '[0-9]'
set #length = #offset - 1
set #offset = #offset + 1
END
if #length > 0
BEGIN
insert into #Numbers
select CAST(SUBSTRING(#temp, #position - #length, #length) as float)
END
set #temp = SUBSTRING(#temp, 1, #position - 1) + SUBSTRING(#temp, #position + 1, LEN(#temp) - #position)
END
declare #return as float
select #return = MAX(number) from #Numbers
return #return
END

convert string into int SQL Server

This is the scenario:
My app will have the following:
A listbox (The checkbox property enabled) that will display a list of Something.
The user will select from the listbox (multiselect) by using the checkbox.
I will loop into All the checked items and store the ID's into an array. I will store the ID's into something like this separating the ID with a comma (1,2,3,4) and then I will use length -1 to delete the last comma.
How can I convert the string 1,2,3,4 into an integer type of data if my stored procedure is like this?
Select * from tblSomething Where ID in (1,2,3,4)
You can use the following SQL function.
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE FUNCTION [dbo].[CommaSeparatedToString]
(
#psCSString VARCHAR(8000)
)
RETURNS #otTemp TABLE(sID VARCHAR(20))
AS
BEGIN
DECLARE #sTemp VARCHAR(50)
WHILE LEN(#psCSString) > 0
BEGIN
SET #sTemp = LEFT(#psCSString, ISNULL(NULLIF(CHARINDEX(',', #psCSString) - 1, -1),
LEN(#psCSString)))
SET #psCSString = SUBSTRING(#psCSString,ISNULL(NULLIF(CHARINDEX(',', #psCSString), 0),
LEN(#psCSString)) + 1, LEN(#psCSString))
INSERT INTO #otTemp VALUES (#sTemp)
END
RETURN
END
And call in your stored procedure like
Select * from tblSomething
Where ID in (SELECT * FROM CommaSeparatedToString('1,2,3,4'))
You can use the
SELECT CAST(MyVarcharCol AS INT) FROM Table
SELECT CONVERT(INT, MyVarcharCol) FROM Table
refer this link
http://msdn.microsoft.com/en-us/library/ms187928.aspx
You need to create dynamic query for this
e.g you are getting list of values in #values paramter so prepare and run the dynamic query like this
DECLARE #query NVARCHAR(500)
DECLARE #values VARCHAR(200)
SET #values='1,2'
SET #query =N'Select * from tblSomething Where ID in ( ' + #values + ')'
SELECT #query
EXEC #Query
Use this function to split the value:
CREATE FUNCTION [dbo].[udfSplitCSV]
(
#String varchar (max),
#Delimiter varchar (10) = ','
)
RETURNS #ValueTable TABLE ([Row] int IDENTITY(1,1), [Value] varchar(max), [Length] int, [Duplicate] int NULL)
BEGIN
DECLARE #NextString varchar(max)
DECLARE #Pos int
DECLARE #NextPos int
IF #String IS NULL RETURN
--Initialize
SET #NextString = ''
SET #String = #String + #Delimiter
--Get position of first Comma
SET #Pos = charindex(#Delimiter,#String)
SET #NextPos = 1
--Loop while there is still a comma in the String
WHILE (#Pos <> 0)
BEGIN
SET #NextString = RTrim(LTrim(SubString(#String,1,#Pos - 1)))
INSERT INTO #ValueTable ([Value], [Length]) VALUES (#NextString, Len(#NextString))
SET #String = SubString(#String,#Pos+1,Len(#String))
SET #NextPos = #Pos
SET #Pos = CharIndex(#Delimiter,#String)
END
UPDATE #ValueTable
SET [Duplicate] = X.Duplicate
FROM #ValueTable VT
INNER JOIN (Select [Row], [Value], Row_Number() OVER (Partition By [Value] ORDER BY [Value], [Row]) as Duplicate FROM #ValueTable) X
ON X.[Row] = VT.[Row]
RETURN
END
-- Select * from dbo.udfSplitCSV('a , c b,c, a', ',')
When you are storing a bunch of IDs into the array, store with single quote.
so it will be ('1','2','3').
Then you no need to covert IDs into integer.

How to change case in string

My table has one column that contain strings like: ” HRM_APPLICATION_DELAY_IN”
I want to perform bellow operations on each row on this column
convert to lower case
remove underscore “_”
change case (convert to upper case) of the character after the underscore like: ” hrm_Application_Delay_In”
Need help for conversion. Thanks for advance
Here is a function to achieve it:
create function f_test
(
#a varchar(max)
)
returns varchar(max)
as
begin
set #a = lower(#a)
while #a LIKE '%\_%' ESCAPE '\'
begin
select #a = stuff(#a, v, 2, upper(substring(#a, v+1,1)))
from (select charindex('_', #a) v) a
end
return #a
end
Example:
select dbo.f_test( HRM_APPLICATION_DELAY_IN')
Result:
hrmApplicationDelayIn
To update your table here is an example how to write the syntax with the function:
UPDATE <yourtable>
SET <yourcolumn> = dbo.f_test(col)
WHERE <yourcolumn> LIKE '%\_%' ESCAPE '\'
For a variable this is overkill, but I'm using this to demonstrate a pattern
declare #str varchar(100) = 'HRM_APPLICATION_DELAY_IN';
;with c(one,last,rest) as (
select cast(lower(left(#str,1)) as varchar(max)),
left(#str,1), stuff(lower(#str),1,1,'')
union all
select one+case when last='_'
then upper(left(rest,1))
else left(rest,1) end,
left(rest,1), stuff(rest,1,1,'')
from c
where rest > ''
)
select max(one)
from c;
That can be extended to a column in a table
-- Sample table
declare #tbl table (
id int identity not null primary key clustered,
str varchar(100)
);
insert #tbl values
('HRM_APPLICATION_DELAY_IN'),
('HRM_APPLICATION_DELAY_OUT'),
('_HRM_APPLICATION_DELAY_OUT'),
(''),
(null),
('abc<de_fg>hi');
-- the query
;with c(id,one,last,rest) as (
select id,cast(lower(left(str,1)) as varchar(max)),
left(str,1), stuff(lower(str),1,1,'')
from #tbl
union all
select id,one+case when last='_'
then upper(left(rest,1))
else left(rest,1) end,
left(rest,1), stuff(rest,1,1,'')
from c
where rest > ''
)
select id,max(one)
from c
group by id
option (maxrecursion 0);
-- result
ID COLUMN_1
1 hrm_Application_Delay_In
2 hrm_Application_Delay_Out
3 _Hrm_Application_Delay_Out
4
5 (null)
6 abc<de_Fg>hi
select
replace(replace(replace(replace(replace(replace(replace(
replace(replace(replace(replace(replace(replace(replace(
replace(replace(replace(replace(replace(replace(replace(
replace(replace(replace(replace(replace(replace(lower('HRM_APPLICATION_DELAY_IN'),'_a','A'),'_b','B'),'_c','C'),'_d','D'),'_e','E'),'_f','F'),
'_g','G'),'_h','H'),'_i','I'),'_j','J'),'_k','K'),'_l','L'),
'_m','M'),'_n','N'),'_o','O'),'_p','P'),'_q','Q'),'_r','R'),
'_s','S'),'_t','T'),'_u','U'),'_v','V'),'_w','W'),'_x','X'),
'_y','Y'),'_z','Z'),'_','')
Bellow two steps can solve problem,as example i use sys.table.user can use any one
declare #Ret varchar(8000), #RetVal varchar(8000), #i int, #count int = 1;
declare #c varchar(10), #Text varchar(8000), #PrevCase varchar, #ModPrefix varchar(10);
DECLARE #FileDataTable TABLE(TableName varchar(200))
INSERT INTO #FileDataTable
select name FROM sys.tables where object_name(object_id) not like 'sys%' order by name
SET #ModPrefix = 'Pur'
DECLARE crsTablesTruncIns CURSOR
FOR select TableName FROM #FileDataTable
OPEN crsTablesTruncIns
FETCH NEXT FROM crsTablesTruncIns INTO #Text
WHILE ##FETCH_STATUS = 0
BEGIN
SET #RetVal = '';
select #i=1, #Ret = '';
while (#i <= len(#Text))
begin
SET #c = substring(#Text,#i,1)
--SET #Ret = #Ret + case when #Reset=1 then UPPER(#c) else LOWER(#c)
IF(#PrevCase = '_' OR #i = 1)
SET #Ret = UPPER(#c)
ELSE
SET #Ret = LOWER(#c)
--#Reset = case when #c like '[a-zA-Z]' then 0 else 1 end,
if(#c like '[a-zA-Z]')
SET #RetVal = #RetVal + #Ret
if(#c = '_')
SET #PrevCase = '_'
else
SET #PrevCase = ''
SET #i = #i +1
end
SET #RetVal = #ModPrefix + #RetVal
print cast(#count as varchar) + ' ' + #RetVal
SET #count = #count + 1
EXEC sp_RENAME #Text , #RetVal
SET #RetVal = ''
FETCH NEXT FROM crsTablesTruncIns INTO #Text
END
CLOSE crsTablesTruncIns
DEALLOCATE crsTablesTruncIns
I'd like to show you my nice and simple solution. It uses Tally function to split the string by pattern, in our case by underscope. For understanding Tally functions, read this article.
So, this is how my tally function looks like:
CREATE FUNCTION [dbo].[tvf_xt_tally_split](
#String NVARCHAR(max)
,#Delim CHAR(1))
RETURNS TABLE
as
return
(
WITH Tally AS (SELECT top (select isnull(LEN(#String),100)) n = ROW_NUMBER() OVER(ORDER BY [name]) from master.dbo.syscolumns)
(
SELECT LTRIM(RTRIM(SUBSTRING(#Delim + #String + #Delim,N+1,CHARINDEX(#Delim,#Delim + #String + #Delim,N+1)-N-1))) Value, N as Ix
FROM Tally
WHERE N < LEN(#Delim + #String + #Delim)
AND SUBSTRING(#Delim + #String + #Delim,N,1) = #Delim
)
)
This function returns a table, where each row represents part of string between #Delim (in our case between underscopes). Rest of the work is simple, just cobination of LEFT, RIGHT, LEN, UPPER and LOWER functions.
declare #string varchar(max)
set #string = ' HRM_APPLICATION_DELAY_IN'
-- convert to lower case
set #string = LOWER(#string)
declare #output varchar(max)
-- build string
select #output = coalesce(#output + '_','') +
UPPER(left(Value,1)) + RIGHT(Value, LEN(Value) - 1)
from dbo.tvf_xt_tally_split(#string, '_')
-- lower first char
select left(lower(#output),1) + RIGHT(#output, LEN(#output) - 1)

T-SQL script or function that will get selected values from a comma delimited string

If I have a string with values like A,B,C,D,E,F, and I wanted to remove the last comma, is there a function or script I can use to do that?
The below example will trim off the last char of a string but wont care if it's a comma or not
DECLARE #s VARCHAR(50)
SET #s = 'a,b,'
SELECT LEFT(#s, LEN(#s)-1)
If I'm understanding you additional question correctly, I believe you want to archive something like the below...
DECLARE #b TABLE
(
[stuff] VARCHAR(2)
)
INSERT INTO #b VALUES('c')
DECLARE #s VARCHAR(MAX)
SET #s = 'a,b,c'
SELECT [stuff]
FROM #b b
INNER JOIN dbo.list(#s) lst
ON lst.val = b.[stuff]
CREATE function [dbo].[list] ( #list VARCHAR(MAX) )
RETURNS #list_table TABLE ([val] VARCHAR(20))
AS
BEGIN
DECLARE #index INT,
#start_index INT,
#val VARCHAR(20)
SELECT #index = 1
SELECT #start_index = 1
WHILE #index <= DATALENGTH(#list)
BEGIN
IF SUBSTRING(#list,#index,1) = ','
BEGIN
SELECT #val = SUBSTRING(#list, #start_index, #index - #start_index )
INSERT #list_table ([val]) VALUES (#val)
SELECT #start_index = #index + 1
END
SELECT #index = #index + 1
END
SELECT #val = SUBSTRING(#list, #start_index, #index - #start_index )
INSERT #list_table ([val]) VALUES (#val)
RETURN
END
The function just splits up the input string into rows in a table with a column "val" - this means you can then pass in a comma delimited string and use it to filter another table.