Sample Header Ad - 728x90

Database Administrators

Q&A for database professionals who wish to improve their database skills

Latest Questions

1 votes
2 answers
66 views
How to extract certificate attributes from a single column and split into many?
In my table I've a field (let say `cert_attr`) which stores [Certificate X.509 Attributes](https://docs.oracle.com/cd/E24191_01/common/tutorials/authz_cert_attributes.html). Here is the example of 3 rows (each line corresponds to a field): "CN=User1, OU=Eng, O=Company Ltd, L=D4, S=Dublin, C=IE" "CN=...
In my table I've a field (let say cert_attr) which stores [Certificate X.509 Attributes](https://docs.oracle.com/cd/E24191_01/common/tutorials/authz_cert_attributes.html) . Here is the example of 3 rows (each line corresponds to a field): "CN=User1, OU=Eng, O=Company Ltd, L=D4, S=Dublin, C=IE" "CN=User2, OU=Eng, O=Company Ltd, L=D2, S=Dublin, C=IE" "OU=Eng, O=Company Ltd" And I'm trying to split the value of a field into separate columns using SELECT in the following way: SELECT SUBSTRING_INDEX(SUBSTRING_INDEX(cert_attr, "CN=", -1), ", ", 1) as CN, SUBSTRING_INDEX(SUBSTRING_INDEX(cert_attr, "OU=", -1), ", ", 1) as OU, SUBSTRING_INDEX(SUBSTRING_INDEX(cert_attr, "O=", -1), ", ", 1) as O, SUBSTRING_INDEX(SUBSTRING_INDEX(cert_attr, "L=", -1), ", ", 1) as L, SUBSTRING_INDEX(SUBSTRING_INDEX(cert_attr, "ST=", -1), ", ", 1) as ST, SUBSTRING_INDEX(SUBSTRING_INDEX(cert_attr, "C=", -1), ", ", 1) as C FROM mytable which works, however there is an issue for the rows which are missing some attributes. So in the case where the attribute is missing in the field's string, I expect the column to be empty, but it returns the whole string instead. The first two row examples are working as expected, which returns the following columns correctly: | CN | OU | O | L | S. | C | | ----- | --- | ----------- | -- | ------ | -- | | User1 | Eng | Company Ltd | D4 | Dublin | IE | | User2 | Eng | Company Ltd | D2 | Dublin | IE | The problem is with the 3rd row example, which I expect to return an empty string when the substring pattern is not found: | CN | OU | O | L | S. | C | | ---------- | --- | ----------- | ---------- | ---------- | ---------- | | OU=Eng,... | Eng | Company Ltd | OU=Eng,... | OU=Eng,... | OU=Eng,... | but instead the whole string is returned. **Question:** Is there any way to return an empty string when SUBSTRING_INDEX() fails to find the substring? Or maybe there is some other function (like a regular expression) or another workaround? My goal is to extract the data into TSV file by having these attributes in separate columns with valid values: mysql mytable cert_attributes.tsv
kenorb (475 rep)
Oct 23, 2020, 07:10 PM • Last activity: Mar 22, 2025, 03:28 PM
-1 votes
2 answers
57 views
MariaDB trigger using Substring gives error "Function does not exist, Check Function Name Parsing in the manual"
I have this trigger as a test. It has to do a lot more. It compiles/saves fine. But when I insert a row, I get an error >#1630 - FUNCTION databasename.SUBSTRING does not exist. Check the 'Function Name Parsing and Resolution' section in the Reference Manual ``` CREATE TRIGGER Staff_BI BEFORE INSERT...
I have this trigger as a test. It has to do a lot more. It compiles/saves fine. But when I insert a row, I get an error >#1630 - FUNCTION databasename.SUBSTRING does not exist. Check the 'Function Name Parsing and Resolution' section in the Reference Manual
CREATE TRIGGER Staff_BI
BEFORE INSERT ON Staff
FOR EACH ROW 
BEGIN
    SET NEW.Salt = SUBSTRING (MD5(RAND()), 1, 32);
    SET NEW.Password = SHA2 (CONCAT(NEW.Password, NEW.Salt), 256);
END;
--- I tried with **SUBSTR** as well, with the same error The knowledgebase did not help. I cant find anything called the **Reference Manual** enter image description here
Rohit Gupta (2126 rep)
Feb 22, 2025, 05:15 AM • Last activity: Feb 22, 2025, 11:18 PM
0 votes
2 answers
2318 views
Extract/parse info between delimiters
I have a column where there are 10 "fields" separated by the pipe character, looks like this: > texthere | somemoretext | sometinghere | moreinfo | evenmorehere | etc | > etc | I've been trying to extract what's between the pipes and I can do the first 2, but after that, my brain gets stuck in an in...
I have a column where there are 10 "fields" separated by the pipe character, looks like this: > texthere | somemoretext | sometinghere | moreinfo | evenmorehere | etc | > etc | I've been trying to extract what's between the pipes and I can do the first 2, but after that, my brain gets stuck in an inception loop and I can't wrap my head around it. eg. Table name is MyTable, column is MyColumn SELECT TOP 10 MyTable.ItemsID, MyTable.MyColumn (SELECT SUBSTRING (MyTable.MyColumn,1,CHARINDEX('|', MyColumn)-1))as Pos1, (SELECT SUBSTRING(MyTable.MyColumn, CHARINDEX('|', MyColumn)+1,CHARINDEX('|', MyColumn))) as Pos2 FROM MyTable I get what I need for Positions 1 and 2, but then for the rest, I'm not sure how to do it. I'm thinking I need to get the index pos of my 3rd pipe but my brain freezes, I tried variations of: SELECT SUBSTRING(MyTable.MyColumn, CHARINDEX(SUBSTRING(MyTable.MyColumn, CHARINDEX('|', MyColumn)+1,CHARINDEX('|', MyColumn)))) as Pos3 I've just looked into REPLACE and PARSENAME functions. With replace I could replace the pipe characters with dots or periods so that PARSENAME can parse the dot delimited values. However, I discovered that PARSENAME is limited to 4 values. I got nice results using STRING_SPLIT however, this function requires compatibility level 130 and I can't alter the DB. My interactions with it is through APIs.
SELECT value
FROM STRING_SPLIT ((select mytable.mycolumn from dbo.mytable), '|');
bravo4one (101 rep)
Apr 4, 2022, 10:37 PM • Last activity: Apr 18, 2024, 12:04 AM
1 votes
1 answers
3160 views
I am trying to get the string between hyphen (-) which is before (+) upto next colon (:)
03/02/2020, 7:41 pm - +91 9999999999: At 7:10; 03/02/2020, 7:41 pm - + abcd : At 7:10; **Note:** The string in between `-` and `:` is not of same length in each record. Please, help me with a solution applicable in such case.
03/02/2020, 7:41 pm - +91 9999999999: At 7:10; 03/02/2020, 7:41 pm - + abcd : At 7:10; **Note:** The string in between - and : is not of same length in each record. Please, help me with a solution applicable in such case.
Salva (13 rep)
Mar 10, 2020, 05:08 AM • Last activity: Mar 5, 2024, 11:16 AM
2 votes
2 answers
538 views
Return part of a string with variable length
I have data in a table column like below: ``` host=0.0.0.0 port=5432 dbname=database_name user=pglogicaluser host=0.0.0.0 port=5432 dbname=database_name2 user=pglogicaluser ``` I want to write a query to get the database names only like below: ``` database_name database_name2 ``` I could come up wit...
I have data in a table column like below:
host=0.0.0.0 port=5432 dbname=database_name user=pglogicaluser
host=0.0.0.0 port=5432 dbname=database_name2 user=pglogicaluser
I want to write a query to get the database names only like below:
database_name
database_name2
I could come up with something like:
select substring(column_name, '.+dbname=(.*)$') from table_name;
However, I couldn't figure how to stop the extraction before the user keyword starts.
Sayad Xiarkakh (532 rep)
Mar 21, 2022, 06:28 PM • Last activity: Sep 3, 2023, 04:21 PM
0 votes
2 answers
176 views
Using a WHERE colname NOT LIKE (select * from otherTable)
So in essence what im trying to do is this: Given `TBL1` (around 8,000 rows) | letters | | -------- | | abababa | | bcbcbcb | | cdcdcdc | and `TBL2` (around 2,000 rows) | letters | | -------- | | ab | | bc | I want to write a query to find every row in `TBL1` that does not contain atleast one of the...
So in essence what im trying to do is this: Given TBL1 (around 8,000 rows) | letters | | -------- | | abababa | | bcbcbcb | | cdcdcdc | and TBL2 (around 2,000 rows) | letters | | -------- | | ab | | bc | I want to write a query to find every row in TBL1 that does not contain atleast one of the substrings in TBL2 It has to be using a subquery because the actual code (cant post here bc its sensitive information) is a pretty complex query with a couple of concatenations and trims etc. Im trying to do this roughly
SELECT * FROM TBL1 WHERE TBL1.letters NOT LIKE '%'|| (SELECT letters FROM TBL2) ||'%'
My intention is to get the following output returned: | letters | | -------- | | cdcdcdc | As the last row does not contain 'ab' or 'bc'. to get an idea what my code looks like i will enclose with with out any identifying information.
SELECT
  *
FROM
  tbl1
WHERE
  tbl1.col1 NOT LIKE '%' ||(
    SELECT
      LTRIM(
        RTRIM(
          CONCAT(
            REPLACE(
              tbl2.col1,
              CONCAT(tbl2.col2, tbl2.col3),
              ""
            ),
            " ",
            tbl2.col2,
            " ",
            tbl2.col3
          )
        )
      )
    FROM
      tbl2
  ) || '%'
Shahzad Ansari (1 rep)
Feb 2, 2023, 10:03 PM • Last activity: Feb 5, 2023, 09:32 PM
3 votes
1 answers
390 views
String Manipulation of the Result from Recursive CTE
Good afternoon everyone I found just one post here within the last year about this, but it doesn't help my situation. I have been working with MySQL and trying to improve my knowledge of recursive CTE. The version of MySQL is 8.0.19 on a Windows device. The table that I have is generated with: ``` D...
Good afternoon everyone I found just one post here within the last year about this, but it doesn't help my situation. I have been working with MySQL and trying to improve my knowledge of recursive CTE. The version of MySQL is 8.0.19 on a Windows device. The table that I have is generated with:
DROP TABLE IF EXISTS test_table;
CREATE TABLE test_table (
  id int(5) NOT NULL AUTO_INCREMENT,
  source varchar(20) NOT NULL,
  destination varchar(20) NOT NULL,
  route varchar (200) NOT NULL,
  open BOOLEAN DEFAULT true,
  PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
Values are entered using:
INSERT INTO test_table VALUES 
  (1, 'STA_A', 'STA_B', 'Line1', true),
  (2, 'STA_B', 'STA_A', 'Line1', true),
  (3, 'STA_B', 'STA_C', 'Line1', true),
  (4, 'STA_C', 'STA_B', 'Line1', true),
  (5, 'STA_C', 'STA_D', 'Line1', true),
  (6, 'STA_D', 'STA_C', 'Line1', true),
  (7, 'STA_D', 'STA_E', 'Line1', true),
  (8, 'STA_E', 'STA_D', 'Line1', true),
  (9, 'STA_K', 'STA_B', 'Line2', true),
  (10, 'STA_B', 'STA_K', 'Line2', true),
  (11, 'STA_B', 'STA_L', 'Line2', true),
  (12, 'STA_L', 'STA_B', 'Line2', true),
  (13, 'STA_L', 'STA_M', 'Line2', true),
  (14, 'STA_M', 'STA_L', 'Line2', true),
  (15, 'STA_M', 'STA_N', 'Line2', true),
  (16, 'STA_N', 'STA_M', 'Line2', true);
Finally, here is the recursive CTE:
SET profiling = 1;
SET @from = 'STA_A';
SET @to = 'STA_M';
SET @via = 'STA_M';
SET @avoid = 'XXXXX';
WITH RECURSIVE cte AS (
	-- Anchor
	SELECT test_table.destination, CONCAT(test_table.source, ' => ', test_table.route, ' => ', test_table.destination) path, 1 length
	FROM test_table
	WHERE test_table.source = @from
	
	UNION ALL

	-- Recursive member
	SELECT test_table.destination, CONCAT(cte.path, ' => ', test_table.route, ' => ', test_table.destination) path, cte.length + 1 length
	FROM cte
	INNER JOIN test_table
	ON test_table.source = cte.destination
	WHERE NOT FIND_IN_SET(test_table.destination, REPLACE(path, ' => ', ','))
	AND open = TRUE
)
SELECT *
FROM cte
WHERE cte.destination = @to
AND FIND_IN_SET(@via, REPLACE(path, ' => ', ','))
AND NOT FIND_IN_SET(@avoid, REPLACE(path, ' => ', ','))
ORDER BY cte.length
LIMIT 500;
SHOW PROFILES;
This pulls successfully the route from Station A to Station M, listing the stations and line segments between the source and destination:
STA_A => Line1 => STA_B => Line2 => STA_L => Line2 => STA_M
What I need to do is remove one of the duplicate line segments (Line2) and the associated station, leaving:
STA_A => Line1 => STA_B => Line2 => STA_M
Is this possible within the CTE, possibly sequential or recursive string manipulation, or would I need to push all the results into a separate "de-duplicating" process? The real database might produce 100 different routes that would need to be de-duplicated in this way and there could be several duplicated line segments in sequence, such as:
STA_A => Line1 => STA_B => Line1 => STA_C => Line1 => STA_D => Line1 => STA_E => Line2 => STA_F => Line2 => STA_G => Line2 => STA_H => Line2 => STA_I => Line2 => STA_J
would de-duplicate to:
STA_A => Line1 => STA_E => Line2 => STA_J
Thank you for your time (and patience!).
nicodemus (33 rep)
Jan 7, 2023, 02:52 PM • Last activity: Jan 8, 2023, 02:20 PM
2 votes
1 answers
402 views
Microsoft SQL Server - Get first n alphanumeric characters with variable length, meeting ABCD-1234 or ABCD-1234567 format
My MS SQL 2019 server version is 15.0.2080.9 (X64) I have a table like | id | message | | -------- | -------------- | | 2003 | ABCD-1234: some text | | 2897 | ABCD-5678 | | 2456 | ABCD-675456: some text | | 3204 | ABCD-4512345 :some text | | 4567 | ABCD-2345 | My requirement is to create another col...
My MS SQL 2019 server version is 15.0.2080.9 (X64) I have a table like | id | message | | -------- | -------------- | | 2003 | ABCD-1234: some text | | 2897 | ABCD-5678 | | 2456 | ABCD-675456: some text | | 3204 | ABCD-4512345 :some text | | 4567 | ABCD-2345 | My requirement is to create another column in SELECT query, for each row to get like | id | message | key | -------- | -------------- | -------------- | | 2003 | ABCD-1234: some text | ABCD-1234 | 2897 | ABCD-5678 | ABCD-5678 | 2456 | ABCD-675456 some text | ABCD-675456 | 3204 | ABCD-4512345 :some text |ABCD-4512345 | 4567 | ABCD-2345 |ABCD-2345 Meaning I need from position 0 till ABCD-1234 format is satisfied discarding empty or any other text after that. I tried LEFT, RIGHT and Substring but could not find a way to get the exact length to meet the regex criteria from position 0. Can you please help me out? Thanks in advance
Ramakrishnan Srinivasan (53 rep)
Nov 9, 2022, 03:16 AM • Last activity: Nov 9, 2022, 11:31 AM
5 votes
2 answers
1795 views
At finding a substring, find the end position as well
A `LIKE` clause can test if a string occurs in another and the `CHARINDEX` function can give the start position of the first match. In my case, I'm interested in the *end position* though, which is, due to the intricacies of collations, not derivable from the start location. For example, in a German...
A LIKE clause can test if a string occurs in another and the CHARINDEX function can give the start position of the first match. In my case, I'm interested in the *end position* though, which is, due to the intricacies of collations, not derivable from the start location. For example, in a German collation (German_PhoneBook_100_CI_AS_SC_UTF8), - occurs in 'Häger' at position 1 and ends at position 2 and - occurs in 'Haeger' at position 1 and ends at position 3. The problem this is for is to mark the matching part of a search result text for the users benefit. I've been thinking about reversing the strings, but then I still can get only the first match with CHARINDEX and in that reversed case I'd need the last. Any ideas anyone?
John (775 rep)
Sep 8, 2022, 03:54 PM • Last activity: Sep 29, 2022, 01:21 AM
0 votes
3 answers
492 views
Finding duplicate letters in a string beginning and ending at certain positions in MariaDB?
I need to find all strings containing double letters in positions between 4th and 10th inclusive. I can find all double letters by '([a-zA-Z])\1{1,3}'; and positions by SELECT SUBSTRING(columnmame, 4, 9 ) FROM mytable; but I do not know how to combine them? so that the following examples are found:...
I need to find all strings containing double letters in positions between 4th and 10th inclusive. I can find all double letters by '([a-zA-Z])\1{1,3}'; and positions by SELECT SUBSTRING(columnmame, 4, 9 ) FROM mytable; but I do not know how to combine them? so that the following examples are found: Liverpool; Sheffield Central. but not Arran. I have tried WITH cte AS ( SELECT *, SUBSTRING(columnmame, 4, 9) AS c FROM mytable ) SELECT * FROM cte WHERE c REGEX '([a-zA-Z])\1{1,3}'; I am aware that MariaDB does not support backreferences such as '\1'.
Bluetail (103 rep)
Aug 25, 2022, 10:06 AM • Last activity: Aug 26, 2022, 08:03 AM
1 votes
3 answers
12841 views
Extracting an an integer value from an xml column
I'm just wondering how I can extract an integer out of an XML column. Currently all the digits are 4 which the below query is able to do. But the number is going to grow to 10,000's soon which will mean 5 digit and this query will not be able to do it. Is there anyway that I can dynamically get any...
I'm just wondering how I can extract an integer out of an XML column. Currently all the digits are 4 which the below query is able to do. But the number is going to grow to 10,000's soon which will mean 5 digit and this query will not be able to do it. Is there anyway that I can dynamically get any integer out that is next in the middle of ` and ` from the Xml column. Any suggestion will be highly appreciated. SELECT SUBSTRING(msg, patindex('%[0-9][0-9][0-9][0-9]%',msg),4) AS DOMAIN FROM table a(NOLOCK) WHERE msg like '
SQLBen (355 rep)
Sep 23, 2014, 10:42 AM • Last activity: Jul 20, 2022, 11:19 AM
4 votes
2 answers
961 views
SQL join on an edited field
I'm trying to join Table1 and Table2 on the Url fields. However all the Urls in Table2 end with a "/" as per the example below: **Table1** ╔═════════════════════╗ ║ Url1 ║ ╠═════════════════════╣ ║ http://site1.com ║ ║ http://site2.com ║ ║ http://site3.com ║ ║ http://site4.com ║ ║ http://site5.com ║...
I'm trying to join Table1 and Table2 on the Url fields. However all the Urls in Table2 end with a "/" as per the example below: **Table1** ╔═════════════════════╗ ║ Url1 ║ ╠═════════════════════╣ ║ http://site1.com ║ ║ http://site2.com ║ ║ http://site3.com ║ ║ http://site4.com ║ ║ http://site5.com ║ ╚═════════════════════╝ **Table2** ╔═════════════════════╗ ║ Url2 ║ ╠═════════════════════╣ ║ http://site1.com/ ║ ║ http://site2.com/ ║ ║ http://site3.com/ ║ ║ http://site4.com/ ║ ║ http://site5.com/ ║ ╚═════════════════════╝ I'm using a SUBSTRING to remove the final character from the Url2 field. This is what my query looks like: SELECT Table1.Url1, SUBSTRING(Table2.Url2, 1, LEN(Table2.Url2) - 1) AS Urlx FROM Table2 LEFT JOIN Table1 ON Urlx = Table1.Url1 However I cannot get the **Urlx** field in the LEFT JOIN clause to resolve. Is it possible to join tables on a manipulated field or have I constructed my query incorrectly?
neptr (43 rep)
Feb 8, 2022, 03:24 PM • Last activity: Feb 23, 2022, 11:38 AM
0 votes
1 answers
3250 views
how to use substring with a delimiter
Employee_M ```none City Emp_Num_ID Cleveland 2164445437/FTTD/JAMES, TYLER/139561151 Tokyo 1261120379/FTTD/BOYD, ADAMS/14468140 Marakech 4049838896/FTTD/SMITH, TULY E/13956144 Houston 7980151429/FTTD/NEARY, HARTMAN/14215411 ``` I'm trying to extract all digits after the third / with substring select...
Employee_M
City		Emp_Num_ID
Cleveland	2164445437/FTTD/JAMES, TYLER/139561151
Tokyo       1261120379/FTTD/BOYD, ADAMS/14468140  
Marakech	4049838896/FTTD/SMITH, TULY E/13956144
Houston	    7980151429/FTTD/NEARY, HARTMAN/14215411
I'm trying to extract all digits after the third / with substring select substr(Emp_Num_ID,/,10) as Emp_ID from Employee_M sometimes we can have between 4 to 10 charterers after the third / so I chose 10 for the length. any idea how to fix that.
Driven (15 rep)
Apr 17, 2019, 08:02 PM • Last activity: Dec 24, 2021, 03:41 PM
-1 votes
1 answers
422 views
Strange behavior with Quotename and substring
I am seeing some behavior that I cannot figure out. We have a sproc that joins a bunch of tables and filters down some pipe-separated (|) values in a column. We cross apply a string splitter (I believe it is very much based on Jeff Moden's splitter) to separate the values. We then use the following...
I am seeing some behavior that I cannot figure out. We have a sproc that joins a bunch of tables and filters down some pipe-separated (|) values in a column. We cross apply a string splitter (I believe it is very much based on Jeff Moden's splitter) to separate the values. We then use the following to pull out the part we want to see based on the position of a tilde, concat some text to it and then wrap it in brackets. QUOTENAME( substring(tr.TableVar, 1, charindex('~', tr.TableVar) - 1) +'_someText' ) The issue that we started to see was an error "Invalid length parameter passed to the LEFT or SUBSTRING function." This would normally be pretty obvious to me: there's a value that does not contain a tilde. *However*, I have verified that every single record this query would return does, in fact, contain a tilde. This is both with an without any filtering done. I verified this with my eyeballs, with searching for any value that has 0 as the charindex value for the tilde, and a literal search for any record that doesn't contain a tilde (no records returned). What makes this weirder to me is that when I remove the QUOTENAME function, there is no error. I can also take the values and place them in a temp table, run the same select on those and it produces no error. I have also tried adding a replace to use search for a caret instead of a tilde (as below)... no error QUOTENAME( substring(tr.TableVar, 1, charindex('^', replace(tr.TableVar,'~','^')) - 1) +'_someText' ) I'm kind of grasping at straws at this point. Sure, we can just use the replace method but we would also like to know *why* we're now experiencing this error (this never happened before). Is there some kind of Unicode character issue with a tilde in the QUOTENAME function? Am I even on the right track? FWIW, we are on Azure SQL and are using collation SQL_Latin1_General_CP1_CI_AS. FYI and example (in fact the *only* value in this DB) looks like this after the split string (no quotes) 'DOG-1~3~_na_~'. Thanks in advance for your time. EDIT: I just went back and removed the joins to check the values without join conditions. There are indeed values that exist without the tilde. I do know that there are some cases when the engine isn't going to follow it's logical order (from, where, group by, etc) so it can effectively try to apply the substring before the filters. However, that leaves me wondering why using QUOTENAME makes that happen, and especially why using a replace doesn't throw the error; my thought would be that would cause the same issue. As always, thanks in advance
scarr030 (115 rep)
Oct 25, 2021, 01:16 PM • Last activity: Oct 25, 2021, 07:54 PM
2 votes
1 answers
2265 views
Replacing a specific string in oracle
I've a database value `'INS. Company Cancelled'` where multiple values are separated by `'.'` I'm trying to replace `'INS'` with `'INSEXP'` my expected result is `'INSEXP. Company Cancelled'` I've tried below two queries to update the field my output is like `'INSEXP. Company Cancelled. Company Canc...
I've a database value 'INS. Company Cancelled' where multiple values are separated by '.' I'm trying to replace 'INS' with 'INSEXP' my expected result is 'INSEXP. Company Cancelled' I've tried below two queries to update the field my output is like 'INSEXP. Company Cancelled. Company Cancelled' update my_table SET column_name = (select replace(column_name, 'INS', 'INSEXP') from my_table WHERE seq_num = 123) WHERE seq_num = 123; update my_table set column_name = replace(column_name, 'INS', 'INSEXP') WHERE seq_num = 123; Could someone please tell me what I'm doing wrong here?
Aravind (193 rep)
Jan 31, 2021, 08:42 AM • Last activity: Jan 31, 2021, 06:34 PM
1 votes
2 answers
1832 views
Mssql subquery inside a substring
I need to remove the last character of my subquery but I cannot figure out how to reference my subquery in the subselect as I need the length of it. The subselect collects all rows and converts them into a single string by appending them with a separator ";". This is what I need: ``` (SUBSTRING( (SE...
I need to remove the last character of my subquery but I cannot figure out how to reference my subquery in the subselect as I need the length of it. The subselect collects all rows and converts them into a single string by appending them with a separator ";". This is what I need: ``` (SUBSTRING( (SELECT d1.name +'; ' FROM data1 d1 inner join data2 d2 on d1.id = d2.id WHERE d1.id = dOfOutterSelect.id ORDER BY d1.CreatedOn FOR XML PATH('') ), LENGTH(),1)) As "Row name",
Symbiose Studios (13 rep)
Dec 4, 2020, 01:51 PM • Last activity: Dec 7, 2020, 01:55 PM
2 votes
1 answers
9864 views
How to Extract SubString between two positions
I have a text column (*emailbody*) in a table (*notification*) which keeps a record of the HTML that went out for a particular email. Somewhere inside that HTML file, there is a line of text that contains the following line: Delayed ${shipmentId} for Carrier Where `${shipmentId}` represents the spec...
I have a text column (*emailbody*) in a table (*notification*) which keeps a record of the HTML that went out for a particular email. Somewhere inside that HTML file, there is a line of text that contains the following line: Delayed ${shipmentId} for Carrier Where ${shipmentId} represents the specific Id that was generated for that particular record. Example: **12345** Basically I want to query the column in the table for all the shipmentId values, which unfortunately will involve getting the string positions between Delayed and for Carrier. I understand this will likely involve using one of Postgres' regular expression functions but I'm not quite sure how to do it, or if there's something a little simpler.
daniel9x (391 rep)
Apr 17, 2018, 03:35 PM • Last activity: Aug 18, 2020, 05:26 AM
0 votes
1 answers
1174 views
Select All Instances of Substring in a String
I have a varchar(max) column that holds a JSON request string. I need a SQL statement for a report that will select all of the instances of that substring. More specifically I need to grab the LoanId Value from that substring entry pulling a result set that contains a row for each LoanId. Any help w...
I have a varchar(max) column that holds a JSON request string. I need a SQL statement for a report that will select all of the instances of that substring. More specifically I need to grab the LoanId Value from that substring entry pulling a result set that contains a row for each LoanId. Any help would be greatly appreciated. A considerably abbreviated JSON string containing the stuff I'm looking for. [ {"loanId":"1111111111","someotherValue":7}, {"loanId":"2222222222","someotherValue":4}, {"loanId":"3333333333","someotherValue":5}, ]
Tim (155 rep)
Feb 22, 2019, 08:44 PM • Last activity: Jul 12, 2020, 07:03 AM
0 votes
1 answers
76 views
SQL Server 2008 - Replacing csv substrings in view-row using data from other table
Using SQL server 2008, is there a way to perform SELECT query in a view replaces a row containing comma-separated values with their corresponding text value from another table? STRING_SPLIT and STRING_AGG is not available in 2008 version. **EDIT:** Added create and insert script CREATE TABLE Data( I...
Using SQL server 2008, is there a way to perform SELECT query in a view replaces a row containing comma-separated values with their corresponding text value from another table? STRING_SPLIT and STRING_AGG is not available in 2008 version. **EDIT:** Added create and insert script CREATE TABLE Data( Id int, Value1 varchar(50) NULL, Value2 int NULL, Value3 datetime ) GO CREATE TABLE CodeValue( Id int, Code varchar(50) NULL ) GO INSERT [dbo].[Data] ([Id], [Value1], [Value2], [Value3]) VALUES (1, N'0;1;2', 43, CAST(N'2020-07-09T00:00:00.000' AS DateTime)) GO INSERT [dbo].[Data] ([Id], [Value1], [Value2], [Value3]) VALUES (2, N'0;2;3', 652, CAST(N'2020-07-03T00:00:00.000' AS DateTime)) GO INSERT [dbo].[Data] ([Id], [Value1], [Value2], [Value3]) VALUES (3, N'2', 1234, CAST(N'2020-07-02T00:00:00.000' AS DateTime)) GO INSERT [dbo].[CodeValue] ([Id], [Code]) VALUES (0, N'Apple') GO INSERT [dbo].[CodeValue] ([Id], [Code]) VALUES (1, N'Orange') GO INSERT [dbo].[CodeValue] ([Id], [Code]) VALUES (2, N'Banana') GO INSERT [dbo].[CodeValue] ([Id], [Code]) VALUES (3, N'Dogmeat') GO Consider my view contains data from two tables; Data and CodeValue, that would look like this: Data Id | Value | Value2 | Value 3 ============================== 1| 0;1;2| some other data 2| 0;2;3| 3| 2 | CodeValue Id | Code ============= 0| Apple 1| Orange 2| Banana 3| Dogmeat So the actual output from the SELECT query in my view would be: View Id | Value ============ 1| Apple, Orange, Banana 2| Apple, Banana, Dogmeat 3| Banana I've messed around with stored procedures and functions, but can't wrap my head around those and how to actually implement this. **EDIT 2:** Tried using STUFF() using the following template: WITH CTE_TableName AS ( SELECT FieldA, FieldB FROM TableName) SELECT t0.FieldA , STUFF(( SELECT ',' + t1.FieldB FROM CTE_TableName t1 WHERE t1.FieldA = t0.FieldA ORDER BY t1.FieldB FOR XML PATH('')), 1, LEN(','), '') AS FieldBs FROM CTE_TableName t0 GROUP BY t0.FieldA ORDER BY FieldA; However I can't seem to join codeValues on split values using homebrew split_string function: CREATE FUNCTION dbo.tvf_SplitString (@stringToSplit VARCHAR(100)) RETURNS @returnList TABLE(Id VARCHAR(5)) AS BEGIN DECLARE @splitValue VARCHAR(5) DECLARE @post INT WHILE CHARINDEX(';', @stringToSplit) > 0 BEGIN SELECT @pos = CHARINDEX(';', @stringToSplit) SELECT @splitValue = SUBSTRING(@stringToSplit, 1, @pos-1) INSERT INTO @returnList SELECT @splitValue SELECT @stringToSplit = SUBSTRING(@stringToSplit, @pos+1, LEN(@stringToSplit -@pos) END INSERT INTO @returnList SELECT @stringToSplit RETURN END
zenith (3 rep)
Jul 9, 2020, 06:57 AM • Last activity: Jul 9, 2020, 09:58 AM
1 votes
1 answers
290 views
Mass update all cells in a column with a substring of it's original value
I need to trim the last seven characters off of all the cells in a column. This query returns the results that I need SELECT test_date, SUBSTRING(test_date FROM 1 FOR CHAR_LENGTH(test_date) - 7) as test from results; I now need to take the computed result from the substring and replace the original...
I need to trim the last seven characters off of all the cells in a column. This query returns the results that I need SELECT test_date, SUBSTRING(test_date FROM 1 FOR CHAR_LENGTH(test_date) - 7) as test from results; I now need to take the computed result from the substring and replace the original values. Here's what the data looks like, if it helps. Data Table
Chaostime (13 rep)
Jun 27, 2020, 01:42 PM • Last activity: Jun 27, 2020, 02:31 PM
Showing page 1 of 20 total questions