i'm looking for a solution how to create a table from this data (which is located on a table in a sql database with the name "table1") with python or sql
tablename | column | datatype | length |
---|---|---|---|
a | 1 | varchar | 5 |
a | 2 | date | 0 |
a | 3 | float | 0 |
b | 1 | varchar | 10 |
b | 2 | varchar | 8 |
b | 3 | float | 0 |
b | 4 | varchar | 50 |
c | 1 | date | 0 |
c | 2 | varchar | 6 |
goal is to create tables (a,b,c)
their columns and their datatype can also be found in the same table
the tricky part is, that the values of "table1" will always be different(dynamic tablenames, columnnames, datatype and length), so i need to write a code, that can reference the values in "table1" and create all tables with their columns (+datatype) found in "table1"
i got this already
DECLARE @n INT = (SELECT COUNT(DISTINCT TABNAME) FROM dbo.Tablenames),
@i INT = '1',
@query VARCHAR(4000)
WHILE @n >= @i
BEGIN
DECLARE @tablename VARCHAR(255) = (Select Top 1 TABNAME FROM
dbo.Tablenames),
@columnname VARCHAR(255), --not properly declared
@datatype VARCHAR(255), --not properly declared
@length VARCHAR(255) --not properly declared
SELECT TOP 1 @tablename
FROM dbo.Tablenames
SET @query = N'CREATE TABLE' + QUOTENAME(@tablename) +
'(' +
@columnname + @datatype + '(' + @length + ')' --this part needs if statement (if not varchar = no '+ '(' + @length + ')''
+ ')'
EXEC (@query)
SET @i+=1
DELETE FROM dbo.Tablenames
WHERE TABNAME = @tableName
END
thanks in advance