A few days ago, they asked this question about Dynamic Columns SQL-Server
here in SO, maybe I can help you.
Otherwise I'll write you a small alternative solution that you can use as a guide for what you need, I think it might work.
You can create dynamic SQL something like this:
- Send the name of the table as a parameter to
SP
- Send
DataTable
with NombreColumna
, TipoDato
to SP
(table defined by the user)
To send list, datatable you need to create TABLE DEFINED BY THE USER
CREATE TYPE [dbo].[MiColumnaTipoDato] AS TABLE(
NombreColumna [NVARCHAR](200) NULL,
TipoDato [NVARCHAR](200) NULL
);
Then, in the SP
, create the cursor to traverse the table and make your dynamic SQL statement.
Create Procedure sp_CrearTablasDinamicas(
@NombreTabla nvarchar(150),
@EsquemaTabla [MiColumnaTipoDato] readonly
)
AS BEGIN
DECLARE @sql NVARCHAR(MAX);
set @SQL= N' Create table '+QUOTENAME(@NombreTabla);
set @SQL =@SQL+ ' Aquí se repite sobre @EsquemaTabla para agregar N Columnas '
EXECUTE sp_executesql @sql
END
For reference QUOTENAME was specifically designed to name names of columns / tables / databases - sysnames. For example, this: SELECT QUOTENAME('abc[]def')
returns [abc[]]def]
while SELECT '[' + 'abc[]def' + ']'
returns [abc[]def]
that is not valid to use as a column / table / name of the database.