Skip to content
Advertisement

How create table with name which name in another table

There is a table in which all the names of the tables are located and I need to create a table with a name from it.

I give id to the input of the stored procedure and by this number I need to pull the name from another table

SELECT FullTableName
FROM dbo.AllTableNames
WHERE Id = 3

result some

schema3.Users

I need create database schema3.Users.

And this table must have fields where need add this schema

[LineId] [bigint] IDENTITY(1,1) NOT NULL,
[HeaderId] [int] NOT NULL,
 CONSTRAINT [PK_Users] PRIMARY KEY CLUSTERED 
(
    [LineId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Id' , @level0type=N'SCHEMA',@level0name=N'shema3', @level1type=N'TABLE',@level1name=N'Users', @level2type=N'COLUMN',@level2name=N'LineId'

how can i create table with Name with i need get from select?

create proc createdb @dbname sysname
as
declare @sql nvarchar(max)
set @sql = 'create database ' + QUOTENAME(@dbname)
exec (@sql)

Advertisement

Answer

The easiest way to create your table would be to build the required sql string and execute it. It would look something like the following (untested):

declare @sql nvarchar(max)

select @sql='CREATE TABLE ' + QuoteName('schema3') + '.' + QuoteName(FullTableName) + '(
    [LineId] [bigint] IDENTITY(1,1) NOT NULL,
    [HeaderId] [int] NOT NULL,
    CONSTRAINT [PK_Users] PRIMARY KEY CLUSTERED ([LineId])
) on [Primary]'
from dbo.AllTableNames
where Id = 3
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement