tags:

views:

70

answers:

1

Hi

In my app, any user can configure which columns to show, reorder and resize columns. To save every user setting, I have a few tables for that.

One of them is called UserColumns, and looks like this:

Id | UserId | ColumnName | DefaultWidth | Width | SortOrder

Is there any way, without dynamically generating the select string and executing it, that I can select columns from a table, but only the columns that exists in the UserColumns table for that specific user?

So a table like ApplicationErrors:

Id | ExceptionMessage | StackTrace | LogDate

The user with id = 1, have got these columns selected: StackTrace, LogDate.

So I want to get a resultset with only StackTrace and LogDate present, ordered by the value of the SortOrder column from the UserColumns table.

Is this possible?

+3  A: 

In order to do the select with unknown columns you will need to dynamically generate the query and execute it.

If you have only a few users then you can create a view, and use create a table that links a view to a user, and you may be able to select based on the view, but, then your application will want to do that, as it can dynamically create a query with an variable table.

James Black
Ok, I see.I think I will just select all the columns from the table, and then when displaying the resultset for the user, I only display those included in the UserColumns table.Or go with the dynamic SQL generation. Is that a bad thing to do, performance wise (or in any other respect) ?
MartinHN
@MartinHN: SQL Server will cache the execution plans for the dynamic SQL, so assuming you're not handling thousands of different queries simultaneously then performance impact should be negligible. To improve the effectiveness of caching, make sure you put whatever you can as parameters (e.g. values in any WHERE clauses).
Todd Owen
Here is an article about performance of dynamic queries over stored procedures: http://weblogs.asp.net/aaguiar/archive/2006/06/22/Stored-Procs-vs-Dynamic-SQL.aspx
James Black