Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extract text between square brackets in TSQL

I have the following query:

DECLARE @value as nvarchar(max)
SET @value   = '(company.[department] LIKE ''Development'')';

I would like to extract the word between brackets keep it in a value and then put as input in a replace function like this.

select replace(@value, @department, 'another_string');

You will say probably why I don't do it immediately with the replace function. The case is that this department string may change dynamically to another string for example country and I would like every time to keep this choice and change it with a value.

like image 996
alexithymia Avatar asked Mar 28 '18 08:03

alexithymia


People also ask

What is [] in SQL query?

The brackets are required if you use keywords or special chars in the column names or identifiers. You could name a column [First Name] (with a space) – but then you'd need to use brackets every time you referred to that column. The newer tools add them everywhere just in case or for consistency.

How do I escape a square bracket in SQL?

To escape square brackets in LIKE you can use another square bracket to escape the original square bracket or use a custom escape character using the ESCAPE keyword in LIKE clause.

How do I slice a string in SQL?

The SUBSTRING() function extracts a substring from a string (starting at any position). Note: The SUBSTR() and MID() functions equals to the SUBSTRING() function.


2 Answers

You can do this in a query via the base string functions:

SELECT
    SUBSTRING(col,
              CHARINDEX('[', col) + 1,
              CHARINDEX(']', col) - CHARINDEX('[', col) - 1) AS output
FROM yourTable;

Caveats include that you only have one bracketed term, and also that this query form of an answer would be usable in your particular scenario.

Demo

like image 96
Tim Biegeleisen Avatar answered Dec 01 '22 06:12

Tim Biegeleisen


your particular case will idealy works with parsenamefunction:

DECLARE @value as nvarchar(max), @department varchar(100);
SET @value = '(company.[department] LIKE ''Development'')';
SET @department = parsename(replace(replace(@value,'[','.'),']','.'),2)

SELECT replace(@value, @department, 'another_string');

will return:

(company.[another_string] LIKE 'Development')

explanation:

replace brackets with dot '.' and your @value will looks like this:

(company..department. LIKE 'Development')

such pattern is similar with:

Server name.Database name.Schema name.Object name

and you can extract the part of string using parsename function, where: 1 = Object name, 2 = Schema name, 3 = Database name, 4 = Server name

link to function here: https://docs.microsoft.com/en-us/sql/t-sql/functions/parsename-transact-sql

DEMO

like image 32
Vasily Ivoyzha Avatar answered Dec 01 '22 06:12

Vasily Ivoyzha