[sql] How to concatenate variables into SQL strings

I need to concatenate a variable table name into my SQL query such as the following...

ALTER FUNCTION fn_myfunction(@KeyValue text)
BEGIN
     INSERT INTO @tmpTbl1
     SELECT @KeyValue AS fld1
     FROM tbl + @KeyValue + KeyValue.fld1

I also attempted the following but it told me I had to declare the table variable?

ALTER FUNCTION fn_myfunction(@KeyValue text, @KeyTable text)
     FROM @KeyTable.fld1

This question is related to sql sql-server-2008

The answer is


You could make use of Prepared Stements like this.

set @query = concat( "select name from " );
set @query = concat( "table_name"," [where condition] " );

prepare stmt from @like_q;
execute stmt;