TRIM forward slash in T-SQL - sql

I have the following code...
TRIM(LEADING '/' FROM ci.Long_description_1) as 'Description',
I am getting the error message
Incorrect syntax near '/'
Whats the best way of writing this?
Thanks

If you are using SQL Server 2017+, you may use TRIM() with a small trick (by default TRIM() removes the specified characters from the start and the end of the string):
SELECT LEFT(
TRIM('/' FROM Long_description_1 + '?'),
LEN(TRIM('/' FROM Long_description_1 + '?')) - 1
) AS Description
FROM (VALUES
(NULL),
('abcd'),
('1234/'),
('////abcd'),
('/folder/subfolder/x.yz')
) ci (Long_description_1)
Result:
Description
----------------------
abcd
1234/
abcd
folder/subfolder/x.yz

I think you want to remove '/' if it is the first character of Long_description_1 column value. TRIM function in SQL Server will not work the way you are expecting.
For this you can write your query like following.
SELECT CASE
WHEN CHARINDEX('/', ci.Long_description_1) = 1
THEN RIGHT(ci.Long_description_1, LEN(ci.Long_description_1) - 1)
ELSE ci.Long_description_1
END AS [Description]
FROM YouTable

Related

Split strings at specified character in SQL

I need to split a string in SQL at a specified character. I need to split TEX_TEXT field at the '(' character. I use it this way, but in the result the '(' is there.
Left(TEX_TEXT, CHARINDEX('(', TEX_TEXT ) ) as GroupName,
I need the result without the '(' charcter, like this: 80, 80 Avant and so on.... Thanks in advance!
try this demo. Using IIF, LEFT and CHARINDEX
declare #mytable table (col1 varchar(20))
insert into #mytable
values ('80 (xxx 123)'),('79'),('100 Avant (d1)')
SELECT
LEFT(col1,
iif(
CHARINDEX('(', col1) -- get location of 'C'
= 0, -- if charindex is 0 then get length of the string
LEN(col1), -- thus this, if you don't check for no '(' then using charindex will return an error
CHARINDEX('(', col1) - 1) -- otherwise get the location of '(' minus 1
)
FROM #mytable
result
80
79
100 Avant
The easiest thing to do is wrap it in a REPLACE() function. As you are splitting and taking the first part you can be sure there will only ever be one occurrence of the opening parenthesis.
REPLACE(Left(TEX_TEXT, CHARINDEX('(', TEX_TEXT ) ), '(', '') as GroupName
Last thing to do is RTRIM the whole lot to ensure there are no trailing spaces.
The best part to this approach is that you don't need to test the data before applying logic so it should work quicker than using an IIf statement

Removing Special character from string sql

my table have column contain data like this.
SQL 2008
97W
125/ 122Q
121/ 118Q
121/ 118S
123/ 120S
112H
111H
i am trying to remove data before / so output will look like as
97W
122Q
118Q
118S
120S
112H
111H
can anyone share experience how can i achieve if came across such scenario.
Thanks,
Try this:
SELECT LTRIM(RIGHT(mycol, LEN(mycol) - CHARINDEX('/', mycol)))
FROM mytable
Demo here
Look at this one
Select LTRIM(SUBSTRING(col, CHARINDEX('/', col) + 1, LEN(col)))
from table
Use a CASE expression to check whether the string contains /, if yes use CHARINDEX to find the index of / and get the right part. Else the string as it is.
Query
SELECT
CASE WHEN your_column_name LIKE '%/%'
THEN LTRIM(RIGHT(your_column_name, CHARINDEX('/', REVERSE(your_column_name), 1) - 1))
ELSE your_column_name END AS new_string
FROM your_table_name;
SQL Fiddle Demo

How to get a id from a url using SQL QUERY. The ID changes dynamically. the database is Sql server 2008

I have url like:
http://mysites.xyz.com/_layouts/ng/ActivityStream.aspx/id/2624D92223261D370D7287C9E83CAEEA/Activity%20Stream%20Post.
I need to get the 2624D92223261D370D7287C9E83CAEEA. But not able to do so. my current query is
SUBSTRING(#URL2,LEN('http://mysites.xyz.com/_layouts/ng/ActivityStream.aspx/id/'),LEN(#URL2)-LEN('http://mysites.xyz.com/_layouts/ng/ActivityStream.aspx/id/')- CHARINDEX('/',REVERSE(#URL2))))
Please suggest.
Try this:
SELECT SUBSTRING(
#URL2,
CHARINDEX('/id/', #URL2)+4,
CHARINDEX('/', #URL2, CHARINDEX('/id/', #URL2)+5)
- (CHARINDEX('/id/', #URL2)+4))
Note: This assumes that the id is always followed by at least one more slash.
Breakdown:
The first argument of the substring is the string that contains the full expression.
The second one is the first index after /id/.
The third one is the desired length - calculated by the first index of / after /id/ - the first index after /id/.
update
To cope with strings that does not contain a slash after the id value, use case:
SELECT SUBSTRING(
#URL,
CHARINDEX('/id/', #URL)+4,
CASE WHEN CHARINDEX('/', #URL, CHARINDEX('/id/', #URL)+5) > 0 THEN
CHARINDEX('/', #URL, CHARINDEX('/id/', #URL)+5)
- (CHARINDEX('/id/', #URL)+4)
ELSE
LEN(#URL)
END
)
If the structure is always the same then you can try:
SELECT REPLACE(RIGHT(#s, LEN(#s) - 58), '/Activity%20Stream%20Post', '')
or:
SELECT REPLACE(REPLACE(#s,'/Activity%20Stream%20Post', ''), 'http://mysites.xyz.com/_layouts/ng/ActivityStream.aspx/id/', '')

Best way to parse and concatenate a string with SQL

I'm trying to turn object_type,ABC,00,DEF,XY string into ABC-00-DEF-XY-
Here's what I've got, I'm wondering if there is a more efficient way?
CONCAT(
REPLACE(
SUBSTR(a.object_name,
INSTR(a.object_name, ',',1,1)+1,
INSTR(a.object_name, ',',1,2)+1
),',','-'
),'-'
)
Clarification: I need to strip off everything up to and including the first comma, replace all remaining commas with dashes, and then add a dash onto the end.
Try this
replace(substr(a.object_name,instr(a.object_name,',',1,1) + 1),',','-') ||'-'
Rexexp_replace() regular expression function can come in handy in this situation as well:
select ltrim(
regexp_replace( col
, '([^,]+)|,([^,]+)', '\2-'
)
, '-'
) as res
from t1
Result:
RES
--------------
ABC-00-DEF-XY-
SQLFiddle Demo
I suggest using the following code:
REPLACE(SUBSTRING(a.object_name,13,LEN(#object_name)-11),',','-') + '-'

How can I remove leading and trailing quotes in SQL Server?

I have a table in a SQL Server database with an NTEXT column. This column may contain data that is enclosed with double quotes. When I query for this column, I want to remove these leading and trailing quotes.
For example:
"this is a test message"
should become
this is a test message
I know of the LTRIM and RTRIM functions but these workl only for spaces. Any suggestions on which functions I can use to achieve this.
I have just tested this code in MS SQL 2008 and validated it.
Remove left-most quote:
UPDATE MyTable
SET FieldName = SUBSTRING(FieldName, 2, LEN(FieldName))
WHERE LEFT(FieldName, 1) = '"'
Remove right-most quote: (Revised to avoid error from implicit type conversion to int)
UPDATE MyTable
SET FieldName = SUBSTRING(FieldName, 1, LEN(FieldName)-1)
WHERE RIGHT(FieldName, 1) = '"'
I thought this is a simpler script if you want to remove all quotes
UPDATE Table_Name
SET col_name = REPLACE(col_name, '"', '')
You can simply use the "Replace" function in SQL Server.
like this ::
select REPLACE('this is a test message','"','')
note: second parameter here is "double quotes" inside two single quotes and third parameter is simply a combination of two single quotes. The idea here is to replace the double quotes with a blank.
Very simple and easy to execute !
My solution is to use the difference in the the column values length compared the same column length but with the double quotes replaced with spaces and trimmed in order to calculate the start and length values as parameters in a SUBSTRING function.
The advantage of doing it this way is that you can remove any leading or trailing character even if it occurs multiple times whilst leaving any characters that are contained within the text.
Here is my answer with some test data:
SELECT
x AS before
,SUBSTRING(x
,LEN(x) - (LEN(LTRIM(REPLACE(x, '"', ' ')) + '|') - 1) + 1 --start_pos
,LEN(LTRIM(REPLACE(x, '"', ' '))) --length
) AS after
FROM
(
SELECT 'test' AS x UNION ALL
SELECT '"' AS x UNION ALL
SELECT '"test' AS x UNION ALL
SELECT 'test"' AS x UNION ALL
SELECT '"test"' AS x UNION ALL
SELECT '""test' AS x UNION ALL
SELECT 'test""' AS x UNION ALL
SELECT '""test""' AS x UNION ALL
SELECT '"te"st"' AS x UNION ALL
SELECT 'te"st' AS x
) a
Which produces the following results:
before after
-----------------
test test
"
"test test
test" test
"test" test
""test test
test"" test
""test"" test
"te"st" te"st
te"st te"st
One thing to note that when getting the length I only need to use LTRIM and not LTRIM and RTRIM combined, this is because the LEN function does not count trailing spaces.
I know this is an older question post, but my daughter came to me with the question, and referenced this page as having possible answers. Given that she's hunting an answer for this, it's a safe assumption others might still be as well.
All are great approaches, and as with everything there's about as many way to skin a cat as there are cats to skin.
If you're looking for a left trim and a right trim of a character or string, and your trailing character/string is uniform in length, here's my suggestion:
SELECT SUBSTRING(ColName,VAR, LEN(ColName)-VAR)
Or in this question...
SELECT SUBSTRING('"this is a test message"',2, LEN('"this is a test message"')-2)
With this, you simply adjust the SUBSTRING starting point (2), and LEN position (-2) to whatever value you need to remove from your string.
It's non-iterative and doesn't require explicit case testing and above all it's inline all of which make for a cleaner execution plan.
The following script removes quotation marks only from around the column value if table is called [Messages] and the column is called [Description].
-- If the content is in the form of "anything" (LIKE '"%"')
-- Then take the whole text without the first and last characters
-- (from the 2nd character and the LEN([Description]) - 2th character)
UPDATE [Messages]
SET [Description] = SUBSTRING([Description], 2, LEN([Description]) - 2)
WHERE [Description] LIKE '"%"'
You can use following query which worked for me-
For updating-
UPDATE table SET colName= REPLACE(LTRIM(RTRIM(REPLACE(colName, '"', ''))), '', '"') WHERE...
For selecting-
SELECT REPLACE(LTRIM(RTRIM(REPLACE(colName, '"', ''))), '', '"') FROM TableName
you could replace the quotes with an empty string...
SELECT AllRemoved = REPLACE(CAST(MyColumn AS varchar(max)), '"', ''),
LeadingAndTrailingRemoved = CASE
WHEN MyTest like '"%"' THEN SUBSTRING(Mytest, 2, LEN(CAST(MyTest AS nvarchar(max)))-2)
ELSE MyTest
END
FROM MyTable
Some UDFs for re-usability.
Left Trimming by character (any number)
CREATE FUNCTION [dbo].[LTRIMCHAR] (#Input NVARCHAR(max), #TrimChar CHAR(1) = ',')
RETURNS NVARCHAR(max)
AS
BEGIN
RETURN REPLACE(REPLACE(LTRIM(REPLACE(REPLACE(#Input,' ','¦'), #TrimChar, ' ')), ' ', #TrimChar),'¦',' ')
END
Right Trimming by character (any number)
CREATE FUNCTION [dbo].[RTRIMCHAR] (#Input NVARCHAR(max), #TrimChar CHAR(1) = ',')
RETURNS NVARCHAR(max)
AS
BEGIN
RETURN REPLACE(REPLACE(RTRIM(REPLACE(REPLACE(#Input,' ','¦'), #TrimChar, ' ')), ' ', #TrimChar),'¦',' ')
END
Note the dummy character '¦' (Alt+0166) cannot be present in the data (you may wish to test your input string, first, if unsure or use a different character).
To remove both quotes you could do this
SUBSTRING(fieldName, 2, lEN(fieldName) - 2)
you can either assign or project the resulting value
You can use TRIM('"' FROM '"this "is" a test"') which returns: this "is" a test
CREATE FUNCTION dbo.TRIM(#String VARCHAR(MAX), #Char varchar(5))
RETURNS VARCHAR(MAX)
BEGIN
RETURN SUBSTRING(#String,PATINDEX('%[^' + #Char + ' ]%',#String)
,(DATALENGTH(#String)+2 - (PATINDEX('%[^' + #Char + ' ]%'
,REVERSE(#String)) + PATINDEX('%[^' + #Char + ' ]%',#String)
)))
END
GO
Select dbo.TRIM('"this is a test message"','"')
Reference : http://raresql.com/2013/05/20/sql-server-trim-how-to-remove-leading-and-trailing-charactersspaces-from-string/
I use this:
UPDATE DataImport
SET PRIO =
CASE WHEN LEN(PRIO) < 2
THEN
(CASE PRIO WHEN '""' THEN '' ELSE PRIO END)
ELSE REPLACE(PRIO, '"' + SUBSTRING(PRIO, 2, LEN(PRIO) - 2) + '"',
SUBSTRING(PRIO, 2, LEN(PRIO) - 2))
END
Try this:
SELECT left(right(cast(SampleText as nVarchar),LEN(cast(sampleText as nVarchar))-1),LEN(cast(sampleText as nVarchar))-2)
FROM TableName