0

I want to get the column from the dynamic string, In my table: MyTable2 I have many columns/fields, which are : MyVarCharColumnName1,MyVarCharColumnName2,MyVarCharColumnName3,MyVarCharColumnName4 These above fields are nvarchar(50), I wonder how I can get the value of them when join with another table as below example:

SELECT
  *,
  CASE
  WHEN Tbl1.MyId IN ('1', '2', '3', '4')
    THEN (SELECT 'MyVarCharColumnName' + bf.MyId
          FROM MyTable2)
  ELSE Tbl1.MyId
  END AS TheNameofId
FROM
  Tbl1

above is wrong because it will return MyVarCharColumnName1 as TheNameofId value instead of the value inside MyVarCharColumnName1

Is there are some sql function that can return the column name from a string? any way to convert 'MyVarCharColumnName1' to column object?

1
  • You can use dynamic sql. Commented May 22, 2018 at 9:25

1 Answer 1

1

As it is confirmed that you have to write dynamic query to do in the same way as you are asking but beside that we can do the same in the following way using CASE

SELECT
  *,
  CASE
      WHEN Tbl1.MyId = 1 THEN MyVarCharColumnName1
      WHEN Tbl1.MyId = 2 THEN MyVarCharColumnName2
      WHEN Tbl1.MyId = 3 THEN MyVarCharColumnName3
      WHEN Tbl1.MyId = 4 THEN MyVarCharColumnName4
      ELSE Tbl1.MyId
  END AS TheNameofId
FROM Tbl1
Sign up to request clarification or add additional context in comments.

4 Comments

Yeah, this is a better approach than dynamic SQL. +1.
I know this way, but the fields are 10 fields, and I don't want make 10 lines, However, I now the table designed not correctly, but that what is exist, and the above sample I provided is simplify the issue, Is there are any other creative idea?
Would you like to go with dynamic solution ??
@Susang No, I don't like dynamic sql, But there are many ms sql functions like COL_NAME or OBJECT_ID; but I can not use them to help

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.