0

I have two database tables, in one of them I have some messages (like a template) and in the second one I have the values that should be replaced in the message.

I'll try to explain myself

In table A I have something like this

Id - Message

1 - "User {0} has logon from {1}"

In table B I have something like this

Id - Id Message - ParamValue - ParamPosition

1 - 1 - Hugo - 0

2 - 1 - Computer A - 1

What I would like to have is a message formed like

User Hugo has logon from Computer A

Something like string.format in c#.

How can I do this and how can I do it no matter how many parameters does the message have?

Thanks for your help!

Hugo Assanti
  • 421
  • 1
  • 8
  • 16

2 Answers2

0

As @Gordon Linoff pointed out in the comments MySQL is not suited for such tasks. If however your Message Table is somewhat "constant" you could try to replace the values like this:

SELECT
  REPLACE(REPLACE(messages.message, '{0}', first_param.ParamValue), 
     '{1}', second_param.ParamValue)
FROM
  messages LEFT JOIN params first_param ON (first_param.message_id = messages.id)
           LEFT JOIN params second_param ON (second_param.message_id = messages.id)

But beware, that solution will only work for at most two parameters.

Martin Schneider
  • 3,268
  • 4
  • 19
  • 29
  • Any idea on how to do it if I have "x" parameters? Some messages can have only one and others could have more than one. I was thinking on maybe examine every character in the message and see if it is a number, if it is i'll search the appropriate value...but I don't think this is a good way – Hugo Assanti Feb 03 '16 at 10:44
0

below code can be used to get the desired result even if you have more than one rows in tableA.

;WITH CTE 
AS
(
    select Msgid,[0] as position0,[1]  as position1
    from
    (
        SELECT Msgid,paramvalue,position
        FROM #tableB
    )pv
    pivot 
    (
       max(paramvalue) FOR position IN ([0],[1])
    )P

)

SELECT
  REPLACE(REPLACE(om.Msg, '{0}', pm.position0),'{1}', pm.position1)
from #tableA om
left join CTE pm ON om.id = pm.Msgid
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Vinod Narwal
  • 169
  • 2