c# use tablename as variable

ÖMER NASUHİ KESKİN 20 Reputation points
2023-01-30T06:44:59.1066667+00:00

How can i use tablename as a variable in sql query?

"select * from table_name "

table_name must be variable.

ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,161 questions
SQL Server
SQL Server
A family of Microsoft relational database management and analysis systems for e-commerce, line-of-business, and data warehousing solutions.
12,706 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,238 questions
0 comments No comments
{count} votes

Accepted answer
  1. PercyTang-MSFT 12,426 Reputation points Microsoft Vendor
    2023-01-30T08:27:45.1533333+00:00

    Hi @ÖMER NASUHİ KESKİN

    Your title and content are somewhat conflicting, and I don't see anything to do with C# from the content. Like Olaf said, you can try dynamic SQL. You can refer to the content in this link.

    https://learn.microsoft.com/en-us/sql/relational-databases/system-stored-procedures/sp-executesql-transact-sql?view=sql-server-ver16

    Best regards,

    Percy Tang


    If the answer is the right solution, please click "Accept Answer". If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our Documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

3 additional answers

Sort by: Most helpful
  1. Viorel 112.1K Reputation points
    2023-01-30T09:40:48.1366667+00:00

    Sometimes you can use an approach like this:

    if @variable = 1
       select * from Table1
    else if @variable = 2
       select * from Table2
    else
       select * from Table3
    
    1 person found this answer helpful.
    0 comments No comments

  2. Olaf Helper 40,741 Reputation points
    2023-01-30T06:58:07.6833333+00:00

    How can i use tablename as a variable in sql query?

    That's not really possible, object names must be fix, you can not use a variable instead.

    One option is dynamic SQL, but belief me, you don't want that. See The Curse and Blessings of Dynamic SQL

    You use C# tag, in which way is it related to?

    0 comments No comments

  3. Erland Sommarskog 101K Reputation points MVP
    2023-01-30T22:25:01.1933333+00:00

    In addition to the other answers: there is a fair chance that your desire to have a dynamic table is due to an incorrect design. Maybe all those many tables should be a single table with one more key column.

    0 comments No comments