1

I would like to create stored procedure, which creates me new table, but the problem is that the table name and column (count and datatypes of columns) is dynamic.

So, the procedure should take probably two parameters: table name and list of columns (in this list are names of columns and datatypes)

Is there any way to do something like this?

5
  • You need to be clear what software and language you are asking about. Is this about some database system? SQL perhaps? Commented Nov 2, 2016 at 11:17
  • Hello, it is Microsoft sql server. Commented Nov 2, 2016 at 12:20
  • There is no point in generating a stored procedure if you are going to change the table or the columns. You gain no advantage - not performance, because the execution plan can't be reused. Not security, because you'll have to generate a SQL string and run it. Not abstraction or simplification, because you end up exposing all the very things you wanted to abstract. Actually, you introduce security problems because your SQL string may be subject to SQL injection Commented Nov 2, 2016 at 12:35
  • Why do you think you need a stored procedure? Why not a view or a query generated by an ORM? Commented Nov 2, 2016 at 12:36
  • Wanting to parameterize table and column names is frequently a symptom of a broken data model - where data items of the same "type" (logical type, e.g. "person's first name", not physical type, such as varchar) have ended up in multiple column(s) (or multiple table(s)). In a well designed data model, any variations should be occurring at the level of data (values in other columns) rather than metadata. Commented Nov 2, 2016 at 13:33

1 Answer 1

1

You can create dynamic SQL something like this.

  • Send Table name as parameter to SP
  • Send DataTable with colunName,DataType to SP (User Defined Table)

For sending list, datatable you need to create USER DEFINED TABLE

CREATE TYPE [dbo].[myColumnDatatyes] AS TABLE(
    columnName [NVARCHAR](200) NULL,
    columnDataType [NVARCHAR](200) NULL
);

Then in the SP use this UDT something like this, create cursor to loop over table and make your dynamic SQL statement.

Create Procedure sp_CreateDynamicTables(
@tableName nvarchar(150),
@tableSchema [myColumnDatatyes] readonly
)
AS BEGIN
 DECLARE @sql NVARCHAR(MAX);

 set @SQL= N' Create table '+QUOTENAME(@tableName);

 set  @SQL =@SQL+ ' Here loop over @tableSchema to add N Columns '

 EXECUTE sp_executesql  @sql
END
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.