Note that there are some explanatory texts on larger screens.

plurals
  1. POUpdate a field with a cascaded string, depending on other fields
    primarykey
    data
    text
    <p>I have the following SQL query (simplified):</p> <pre><code>UPDATE myTable SET Phone1 = 049 ,Phone2 = 123 ,Class = --??? WHERE Project = 'ABC' </code></pre> <p>So I just want to set some default values for every project 'ABC'. For the Class field I want the following: There are 5 other fields in the table, Class1 to Class5, each field contains a 1 or a 0. If Class1 is 1, then Class should contain "C1". If Class1 and Class3 contain a 1, then Class should be "C1 + C3". If all ClassN fields contain a 1 it should be "C1 + C2 + C3 + C4 + C5" and so on.</p> <p>Now that's not too hard either:</p> <pre><code>DECLARE @Class NVARCHAR(100) DECLARE @Class1 INT = 0 DECLARE @Class2 INT = 0 DECLARE @Class3 INT = 0 DECLARE @Class4 INT = 0 DECLARE @Class5 INT = 0 SET @Class = CASE WHEN ISNULL(@Class1, 0) = 1 THEN 'C1 + ' ELSE '' END SET @Class = ISNULL(@Class, '') + CASE WHEN ISNULL(@Class2, 0) = 1 THEN 'C2 + ' ELSE '' END SET @Class = ISNULL(@Class, '') + CASE WHEN ISNULL(@Class3, 0) = 1 THEN 'C3 + ' ELSE '' END SET @Class = ISNULL(@Class, '') + CASE WHEN ISNULL(@Class4, 0) = 1 THEN 'C4 + ' ELSE '' END SET @Class = ISNULL(@Class, '') + CASE WHEN ISNULL(@Class5, 0) = 1 THEN 'C5 + ' ELSE '' END -- Remove last + IF (LEN(@Class) &gt; 0) SET @Class = LEFT(ISNULL(@Class, ''), LEN(@Class) - 2) SELECT @Class </code></pre> <p>But now I am just not sure how to combine those two things the best way. How can I combine them the best way?</p> <p>My best idea right now is to create a scalar-valued function and return the string.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload