Create table from metadata??

Im working on creating a table from the meta data stored in someother table. is there any easy or anyway doing this. i tried and gave up.

here is how metadata table looks like

TABNAME  COLNAME  DATATYPE   LENGTH
usaall              regionid           int            NULL
usaall         region               varchar      60
usaall              account        varchar            50

from the above metadata i want to create a table called USAALL with the columns mentioned.
LVL 8
k_rasuriAsked:
Who is Participating?
 
nmcdermaidConnect With a Mentor Commented:
ah I see.. disregard my comment.

Solution that comes to mind is build a DDL script and run it. It will open you up to security risks though. If anyone can change your table so that the datatype is /* */ DROP DATABASE X, then it'll drop the database. (kind of an injection attack)

This is untested......


DECLARE @TableName VARCHAR(100)
DECLARE @DDL VARCHAR(4000)

SET @TableName = 'usaall'

-- create table
SET @DDL = 'CREATE TABLE [' + @TableName + '] ( '

-- columns
SELECT
@DDL = @DDL + COLNAME + ' ' + DATATYPE + ' ' + ISNULL([LENGTH],'') + ', '
FROM MetaData
WHERE TABNAME = @TableName

-- Remove trailing comma and add closing bracket
SET @DDL = LEFT(@DDL,LEN(@DDL)-2) + ' )'

-- Run the DDL
EXEC (@DDL)



PS any reason you aren't just creating one table with 'usaall' in it, along with all the other regions, and just filtering on it?
0
 
nmcdermaidCommented:
SELECT *
INTO YourNewTable
FROM YourExistingTable
WHERE 1=0


Will create an empty table called YourNewTable with similar meta data to YourExistingTable
0
All Courses

From novice to tech pro — start learning today.