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?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

nmcdermaidCommented:
SELECT *
INTO YourNewTable
FROM YourExistingTable
WHERE 1=0


Will create an empty table called YourNewTable with similar meta data to YourExistingTable
0
nmcdermaidCommented:
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

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Microsoft SQL Server 2005

From novice to tech pro — start learning today.