Search code examples
sqlsql-serverparameterscreate-table

Can I use parameters in a CREATE query?


Actually I have 2 questions, both in SQL Server.

  1. There's a query like "Create Table" but for Create columns? If it exist, please, how it is?

  2. I need to use a "Create Table" but using parameters, but I don't know if that is possible. For example:

    @table_name string,
    @column_name1 int,
    @column_name2 int,
    @column_name3 int
    
    CREATE TABLE @table_name
        (
        @column_name1,
        @column_name2,
        @column_name3
        ....
        );
    

Obviously that's only what I have in mind and doesn't work. There is a right way to do it?

I appreciate your help!


Solution

  • For #1, use ALTER TABLE command.

    For #2, how are you executing the query? You can create a string variable first with the complete command and table name as parameter and then execute the query. Something like:

    declare @ CustomerID int 
    
    set @ CustomerID = 3262833
    
    declare @sql nvarchar(1000)
    
    
    
    set @sql = N'SELECT * FROM [dbo].[Customers] AS [tbCustomers] WITH (NOLOCK) 
    
    WHERE  tbCustomers.ID = '+ + cast(@CustomerID as nvarchar(10))   
    
    
    
    exec (@sql)