I want to execute a sql query by using dynamic table name.
I tried below codes but none of these works for me and throws syntax error.
exec sp_executesql N'SELECT * FROM @Table1 D WITH (NOLOCK)',
N'@Table1 nvarchar(40)',@Table1=N'master.dbo.ABCD_data'
OR
exec sp_executesql N'SELECT * FROM master.dbo.+@Variable1+_data D WITH (NOLOCK)',
N'@Variable1 nvarchar(4),',@Variable1=N'ABCD'
Can anybody help me in creating this dynamic table name ?
I get this query from sql profiler. Actually i m executing it in c# code and got this in profiler.
My C# code is very simple, its kind of this:
string query = @"SELECT * FROM master.dbo.+@Variable1+_data D WITH (NOLOCK)";
SqlCommand cmd = new SqlCommand();
cmd.CommandText = query;
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("@Variable1", "ABCD");
DataTable dt = new DataTable();
using (SqlDataAdapter adapter = new SqlDataAdapter(cmd))
{
adapter.Fill(dt);
}