ale*_*mia 5 t-sql sql-server string replace extract
I have the following query:
DECLARE @value as nvarchar(max)
SET @value = '(company.[department] LIKE ''Development'')';
Run Code Online (Sandbox Code Playgroud)
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');
Run Code Online (Sandbox Code Playgroud)
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.
Tim*_*sen 10
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;
Run Code Online (Sandbox Code Playgroud)
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.
您的具体情况理想地适用于parsename功能:
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');
Run Code Online (Sandbox Code Playgroud)
将返回:
(company.[another_string] LIKE 'Development')
Run Code Online (Sandbox Code Playgroud)
解释:
将括号替换为点“.” 你的@value将如下所示:
(company..department. LIKE 'Development')
这种模式类似于:
Server name。Database name。Schema name。Object name
您可以使用函数提取字符串的一部分parsename,其中:1 = Object name, 2 = Schema name, 3 = Database name,4 = Server name
链接到此处的函数: https: //learn.microsoft.com/en-us/sql/t-sql/functions/parsename-transact-sql