简体   繁体   中英

Use part of string as variable?

There's something I'm trying to do, I don't think it's possible but maybe I'm wrong.

It is in teradata so I can't use variables.

I have a table that contains different messages as strings:

Ie, column MSG contains 'Hello, how are you today?'

And a table that contains different users with user_id and user_name.

Then, separately, I am using:

SELECT
  MSG,
  USER_ID,
  USER_NAME
FROM MSG_TABLE
INNER JOIN PERSON_TABLE
  ON PERSON_ID.ID = MSG_TABLE.ID

Is there a way to modify the message in the message table, so that when I select the message, part of the string acts as if retrieving information from the person table?

So that the MSG in the table would be something like 'Hello @@@, how are you today?' and when I run the query above I would get

 | 'Hello Peter, how are you today?' | 1765 | Peter.

I would suggest you to store the value in the 'MSG' column as something like this:

'Hello {username}, how are you today?'

Then, you can just use the REPLACE function

SELECT
  OREPLACE(MSG, '{username}', USER_NAME) AS NEW_MSG,
  USER_ID,
  USER_NAME
FROM MSG_TABLE
INNER JOIN PERSON_TABLE
  ON PERSON_ID.ID = MSG_TABLE.ID

Don't know Terradata, but this should work:

SELECT
  OREPLACE(MSG, '@@@', USER_NAME),
  USER_ID,
  USER_NAME
FROM MSG_TABLE
INNER JOIN PERSON_TABLE
  ON PERSON_ID.ID = MSG_TABLE.ID

Given: OREPLACE

Without changing your existing pattern:

select 
  strtok(MSG, ',', 1) || ' ' || USER_NAME || ', ' || strtok(MSG, ',', 2), USER_ID, USER_NAME
FROM MSG_TABLE
INNER JOIN PERSON_TABLE
  ON PERSON_ID.ID = MSG_TABLE.ID;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM