i’m trying to create a dynamic sql statement either thru sql code or c# code. For example, I’d like to generate a result set based on a string containing a table name. Currently, I am doing this thru c# code.
My current issue is I’d like to generate a search similar to following
select * from customers
where ContactName+City like '%Berlin%'
so I’m thinking given a table name as a string parameter I need to somehow produce a string variable 'ContactName+City+etc' to build part of the search
I’m open to any other ideas as well.
var sql = string.Format(@"
select * from {0}
where {1} like '%criteria%'"
, variable_table
, "column1+column2+columnX"); //need function here to produce this string based on variable table?
Basically, how would I create a string that concatenates a variable number of columns together ('ContactName+City+etc') based on a variable_table?
You can do this purely in SQL as well. But as you have already done this in C# and you need only to get the list of columns based on the table name, try this.
Create a SQL udf as below.
OUTPUT:
Column1 + Column2 + ….. + ColumN
You may have to adjust varchar limits, validations as required.