1

次の方法で一連のデータを保存しています。

Word of various kinds (ANT\username1) and even more words
This is another row, the words are random (ANT\username2)
Thankfully the username only ever shows once (ANT\username1)

上記は3つの別々の行を表しています。

このデータの一般的なフローは次のとおりです。

  • 括弧はテキストのどこにでも表示できます
  • 各文字列のユーザー名部分(ANT \ usernamex)は一度だけ表示されます
  • ユーザー名の部分の前後のテキストは、常に異なる長さです。
  • ユーザー名のテキストが常に存在するとは限りません

おそらくすでにお察しのとおり、私が行う必要があるのは、各行からユーザー名を取得し、それが存在しない場合はnullを返すことです。残念ながら、これにアプローチする方法がわかりません。left()関数とright()関数を試してみましたが、他にこれに取り組む方法がわかりません。タスクを実行するためにいくつかの関数を使用する回答に、ロジックの流れを説明する簡単な宣伝文があれば幸いです(したがって、関数のドキュメントを読んで学ぶことができます)。

4

1 に答える 1

1

データが期待どおりでない場合の具体的な結果に注意してください。これは正確に format で機能します'(ANT\....)'

-- sample table
create table t(s varchar(max));
insert t select 
'Word of various kinds (ANT\) blank' union all select
'Word of various kinds (ANT) blank' union all select
'Word of various kinds (ANT\ no closing' union all select
'Word of various kinds (ANT\(ANT\me) double up' union all select
'' union all select
'(ANT\' union all select
null union all select
'Word of various kinds (ANT\username1) and even more words' union all select
'This is another row, the words are random (ANT\username2)' union all select
'Thankfully the username only ever shows once (ANT\username1)';

-- Query
select Original = s,
       Extracted = nullif(STUFF(LEFT(s, CharIndex(')',s+')',
                   PatIndex('%(ANT\%', s)) -1), 1,
                   PatIndex('%(ANT\%', s + '(ANT\')+4,''),'')
from t;
于 2012-10-31T01:01:51.740 に答える