Tuesday, March 27, 2012

Create a Table dynamically

Is it possible to create a table dynamically ? I would like to do
something like this:
DECLARE @.TableName varchar(100)
SET @.TableName = 'toto'
CREATE TABLE @.TableName
It returns a syntax error.
Thank you.jerome.bellan...@.lycos.com wrote:
> Is it possible to create a table dynamically ? I would like to do
> something like this:
> DECLARE @.TableName varchar(100)
> SET @.TableName = 'toto'
> CREATE TABLE @.TableName
> It returns a syntax error.
> Thank you.
Why would you want to do that though? Good design practice generally
requires a schema that is static at runtime.
Creating tables dynamically might occassionally be useful during
development and you can use TSQL's EXEC statement for that. If you
attempt the same in transactional production environment however you
would pay a heavy price in terms of scalability, security and
manageability.
David Portas, SQL Server MVP
Whenever possible please post enough code to reproduce your problem.
Including CREATE TABLE and INSERT statements usually helps.
State what version of SQL Server you are using and specify the content
of any error messages.
SQL Server Books Online:
http://msdn2.microsoft.com/library/ms130214(en-US,SQL.90).aspx
--|||try this...
declare @.tablename varchar(20)
select @.tablename = 'table'
EXEC ('CREATE TABLE ' + @.tablename + ' ( col1 varchar(20))')
Immy
<jerome.bellanger@.lycos.com> wrote in message
news:1141039414.594591.289750@.i39g2000cwa.googlegroups.com...
> Is it possible to create a table dynamically ? I would like to do
> something like this:
> DECLARE @.TableName varchar(100)
> SET @.TableName = 'toto'
> CREATE TABLE @.TableName
> It returns a syntax error.
> Thank you.
>|||Thank you. It is perfect.|||Not like this.
Try this, instead:
DECLARE @.TableName varchar(100)
SET @.TableName = 'toto'
exec ('CREATE TABLE ' + @.TableName + ' (column1 int)' )
Cheers.
Deck
jerome.bellanger@.lycos.com wrote:
> Is it possible to create a table dynamically ? I would like to do
> something like this:
> DECLARE @.TableName varchar(100)
> SET @.TableName = 'toto'
> CREATE TABLE @.TableName
> It returns a syntax error.
> Thank you.

No comments:

Post a Comment