SQL Server substring without upper bound - sql

What is the best way in SQL Server to do
SELECT
SUBSTRING('CATCH ME IF YOU CAN', 2, 10000)
-- ATCH ME IF YOU CAN
with no upper bound?

Use STUFF instead (STUFF (Transact-SQL)):
SELECT STUFF('CATCH ME IF YOU CAN',1,1,'');
Here, STUFF replaces 1 character, from position 1 with the string ''. The 2nd parameter is the start position, and the 3rd is the number of characters (from that position) to replace. The 4th is the replacement string.
So, as a further example, you could do something like this:
SELECT STUFF('2019-07-09 11:38:00',11,1,'T');
This replaces 1 character from position 11 with the character 'T', which returns '2019-07-09T11:38:00', changing the above value to the ISO8601 format. As you can see, the length of the string to replace does not need to be the same length as the replacement string as well (in fact, the 3rd parameter can have a value of 0, meaning that no characters are replaced and the "replacement" string is simply injected into the existing value).

Using LEN() with variable
DECLARE #Val AS VARCHAR (MAX) = 'CATCH ME IF YOU CAN';
SELECT SUBSTRING(#Val, 2, LEN(#Val));
or directly with LEN()
SELECT SUBSTRING('CATCH ME IF YOU CAN', 2, LEN('CATCH ME IF YOU CAN'));

You can use RIGHT() function, combined with LEN().
All you have to do is subtract from LEN() the number of chars that you want to exclude from the start of the string:
SELECT RIGHT('CATCH ME IF YOU CAN', LEN('CATCH ME IF YOU CAN') - 1)

Related

Replace first char in text column

I have codes in a text column, for example, e12312312 E123123123 need to write sql query who make every value in a column with capital E my database is postgresql
You can use Postgres string function initcap() to turn the first character of a string to upper case and the rest of the string to lower case : since the rest of your strings is made of digits only, this should work:
select initcap('e12312312')
If your string may contain other upper case letters than you do not want to lower, then you can use left(), right() and upper():
select upper(left('e12312312ABC', 1)) || right('e12312312ABC', -1);

SQL: Finding dynamic length characters in a data string

I am not sure how to do this, but I have a string of data. I need to isolate a number out of the string that can vary in length. The original string also varies in length. Let me give you an example. Here is a set of the original data string:
:000000000:370765:P:000001359:::3SA70000SUPPL:3SA70000SUPPL:
:000000000:715186816:P:000001996:::H1009671:H1009671:
For these two examples, I need 3SA70000SUPPL from the first and H1009671 from the second. How would I do this using SQL? I have heard that case statements might work, but I don't see how. Please help.
This works in Oracle 11g:
with tbl as (
select ':000000000:370765:P:000001359:::3SA70000SUPPL:3SA70000SUPPL:' str from dual
union
select ':000000000:715186816:P:000001996:::H1009671:H1009671:' str from dual
)
select REGEXP_SUBSTR(str, '([^:]*)(:|$)', 1, 8, NULL, 1) data
from tbl;
Which can be described as "look at the 8th occurrence of zero or more non-colon characters that are followed by a colon or the end of the line, and return the 1st subgroup (which is the data less the colon or end of the line).
From this post: REGEX to select nth value from a list, allowing for nulls
Sorry, just saw you are using DB2. I don't know if there is an equivalent regular expression function, but maybe it will still help.
For the fun of it: SQL Fiddle
first substring gets the string at ::: and second substring retrieves the string starting from ::: to :
declare #x varchar(1024)=':000000000:715186816:P:000001996:::H1009671:H1009671:'
declare #temp varchar(1024)= SUBSTRING(#x,patindex('%:::%', #x)+3, len(#x))
SELECT SUBSTRING( #temp, 0,CHARINDEX(':', #temp, 0))

Transact SQL replace part of string

Is it possible to delete part of string using regexp (or something else, may be something like CHARINDEX could help) in SQL query?
I use MS SQL Server (2008 most likely).
Example: I have strings like "[some useless info] Useful part of string" I want to delete parts with text in brackets if they are in line.
Use REPLACE
for example :
UPDATE authors SET city = replace(city, 'To Remove', 'With BLACK or Whatever')
WHERE city LIKE 'Salt%'; // with where condition
You can use the PATINDEX function. Its not a complete regular expression implementation but you can use it for simple things.
PATINDEX (Transact-SQL)> Returns the starting position of the first occurrence of a pattern in a specified expression, or zeros if the pattern is not found, on all valid text and character data types.
OR You can use CLR to extend the SQL Server with a complete regular expression implementation.
SQL Server 2005: CLR Integration
SELECT * FROM temp where replace(replace(replace(url,'http://',''),'www.',''),'https://','')='"+url+"';
You can use STUFF to insert a string into another string. It deletes a specified length of characters in the first string at the start position and then inserts the second string into the first string at the start position.
For example, the code below, replaces the 5 with 666666:
DECLARE #Variable NVARCHAR(MAX) = '12345678910'
SELECT STUFF(#Variable, 5, 1, '666666')
Note, that the second argument is not a string, it is a position and you are able to calculate it position using CHARINDEX for example.
Here is your case:
DECLARE #Variable NVARCHAR(MAX) = '[some useless info] Useful part of string'
SELECT STUFF(
#Variable
,CHARINDEX('[', #Variable)
,LEN(SUBSTRING(#Variable, CHARINDEX('[', #Variable), CHARINDEX(']', #Variable) - LEN(SUBSTRING(#Variable, 0, CHARINDEX('[', #Variable)))))
,''
)
Finally helps REPLACE, SUBSTRING and PATINDEX.
REPLACE(t.badString, Substring(t.badString , Patindex('%[%' , t.badString)+1 , Patindex('%]%' , t.badString)), '').
Thanks to all.

SQL Select by condition on a integer field

I have an integer column in my table. It is product id and has values like
112233001
112233002
113311001
225577001
This numbering (AABBCCDDD) is formed of 4 parts:
AA : first level category
BB : second level category
CC : third level category
DDD : counter
I want to check condition in my SELECT statement to select rows that for example have BB = 33 and AA = 11
Please help
Would this suffice:
select x from table where field >= 113300000 and field < 113400000
SELECT * FROM YOURTABLE
WHERE
substr(PRODUCT_ID, 3, 2)='33'
AND
substr(PRODUCT_ID, 1, 2)='11'
OR
SELECT * FROM YOURTABLE
WHERE
PRODUCT_ID LIKE '11%33%'
and yes in short you have to convert to string
reference of substr
Purpose
The SUBSTR functions return a portion of char, beginning at character position, substring_length characters long. SUBSTR calculates lengths using characters as defined by the input character set. SUBSTRB uses bytes instead of characters. SUBSTRC uses Unicode complete characters. SUBSTR2 uses UCS2 code points. SUBSTR4 uses UCS4 code points.
If position is 0, then it is treated as 1.
If position is positive, then Oracle Database counts from the beginning of char to find the first character.
If position is negative, then Oracle counts backward from the end of char.
If substring_length is omitted, then Oracle returns all characters to the end of char. If substring_length is less than 1, then Oracle returns null.
char can be any of the datatypes CHAR, VARCHAR2, NCHAR, NVARCHAR2, CLOB, or NCLOB. Both position and substring_length must be of datatype NUMBER, or any datatype that can be implicitly converted to NUMBER, and must resolve to an integer. The return value is the same datatype as char. Floating-point numbers passed as arguments to SUBSTR are automatically converted to integers.
Select field from table where substr(field,,) = value
This seems like it could work. Otherwise you may have to cast them as strings and parse the values out that you need which would make your queries much slower.
SELECT *
FROM table t
WHERE t.field >= 113300000
AND t.field < 113400000
u need to use _ wildcard char -
SELECT *
FROM TABLE
WHERE
FIELD LIKE '1133_____'
here, each _ is for one char. So you need to put the same number of _ to keep the length same

Split string and replace

I have a varchar column with Url's with data that looks like this:
http://google.mews.......http://www.somesite.com
I want to get rid of the first http and keep the second one so the row above would result in:
http://www.somesite.com
I've tried using split() but can't get it to work
Thanks
If you are trying to do this using T-SQL, you can try something in the lines of:
-- assume #v is the variable holding the URL
SELECT SUBSTRING(#v, PATINDEX('%_http://%', #v) + 1, LEN(#v))
This will return the start position of the first http:// that has before it at least one character (hence the '%_' before it and the + 1 offset).
If the first URL always starts right from the beginning of the string, you can use SUBSTRING() & CHARINDEX():
SELECT SUBSTRING(column, CHARINDEX('http://', column, 2), LEN(column))
FROM table
CHARINDEX simply searches a string for a substring and returns the substring's starting position within the string. Its third argument is optional and, if set, specifies the search starting position, in this case it's 2 so it didn't hit the first http://.