0
votes

I want to create a table with 2 columns: Name of the customer of type varchar and age of type int.

My code:

CREATE PROCEDURE CreateTable 
    (@tablename varchar(50), 
     @column varchar(50),
     @type varchar(50),
     @column2 varchar(20), 
     @type2 int, 
     @extra varchar(20) = NULL)
AS
BEGIN
    DECLARE @sqlQuery AS varchar(MAX)
    SET @sqlQuery = 'CREATE TABLE ' + @tablename +  '( id int '+ @column +' ' + @type + @column2 +' ' + @type2+'  PRIMARY KEY(id))'

    PRINT (@sqlQuery)
    EXEC (@sqlQuery)
END
GO

EXEC CreateTable 'Customers', 'Name', 'varchar(50)', 'Age', 'int'

The error is:

Procedure or function CreateTable has too many arguments specified

I don't know where my error is. Please help me.

1
I don't get that error: dbfiddle.uk/…. - Gordon Linoff

1 Answers

1
votes

Should be OK now:

CREATE PROCEDURE CreateTable (
    @tablename VARCHAR(50)
    ,@column VARCHAR(50)
    ,@type VARCHAR(50)
    ,@column2 VARCHAR(20)
    ,@type2 VARCHAR(50)
    ,@extra VARCHAR(20) = NULL
    )
AS
BEGIN
    DECLARE @sqlQuery AS VARCHAR(MAX)

    SET @sqlQuery = 'create table ' + @tablename + '( id int ,' + @column + '  ' + @type + ' , ' + @column2 + ' ' + @type2 + '  PRIMARY KEY(id))'

    PRINT (@sqlQuery)

    EXEC (@sqlQuery)
END
GO

EXEC CreateTable 'Customers'
    ,'Name'
    ,'varchar(50)'
    ,'Age'
    ,'int'

If you compare the parameters you will find the type of @type2 was specified as int while it should be varchar to be part of the executed statement.

You were also missing comma(,) in your executable string inside the stored procedure.