1

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?

2
  • Do you want to select all the columns in the variable_table or only specific set of columns ? Commented Dec 5, 2012 at 5:27
  • I'm thinking all columns because I can create a view if I want to limit the columns, right? Commented Dec 5, 2012 at 13:46

2 Answers 2

2

Why not simply this:

      select * from variable_table_name
      WHERE column1+column2+columnX like '%criteria%'
Sign up to request clarification or add additional context in comments.

Comments

1

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.

CREATE FUNCTION funcReturnAllColumns
(
    @tableName VARCHAR(50)
)
RETURNS VARCHAR(500)
BEGIN

DECLARE @ID INT
DECLARE @ALLColumns VARCHAR(500)

SET @ALLColumns = ''

SELECT @ID = id
FROM sys.sysobjects
WHERE name = @tableName


SELECT @ALLColumns = @ALLColumns + '+' + name 
FROM sys.syscolumns
WHERE id = @ID

RETURN SUBSTRING(@ALLColumns,2,LEN(@ALLColumns))

END


SELECT dbo.funcReturnAllColumns('table_name')

OUTPUT: Column1 + Column2 + ..... + ColumN

You may have to adjust varchar limits, validations as required.

Comments

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.