4

How can i create a view in SQL Server,where columns are defined and appear according to a value stored in another table.These columns are almost identically calculated by a function but their number is set from another table's record.

2 Answers 2

5

This is not possible with a view because SQL Server queries are always statically typed in the sense that both column count, names and types are statically known at execution time.

You need dynamic SQL for dynamic columns.

Views do not support dynamic SQL. You have to find some other way of returning the data, maybe with one row per logical column.

Sign up to request clarification or add additional context in comments.

2 Comments

can you explain the last step with an example so it seems clear?
Example: You want to return one column per month. As this is not possible, you return one row per month. Instead of (Jan, Feb, Mar, ...) you return (Jan), (Feb), (Mar) from the view.
0

You can create an inline Table-valued function and define your fields and return the table then call the function inside your view.

1 Comment

Is there a way to make an inline TVF have a dynamic number of columns? I think the same restrictions as for views apply in this regard.

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.