2015-05-10 52 views
0

我正在设计一个包含90多列的表。创建表SQL Server其中列名是从另一个表中选择colName

比方说,表名是table_fromCol。所有这些列名称都是表中同一列的值。

假设表table_colName包含:

id colName 
----------------- 
1  Price 
2  Quantity 
3  Vat 
4  Custom Duty 
5  Maximum Price 
6  Discount 

我想创建一个表,所有这些列名。

现在创建一个表table_fromCol

其设计的看法是:

Columns  datatype  null 
---------------------------------- 
id    int   false 
Price   varchar  true 
Quantity  varchar  true 
Vat   varchar  true 
Custom Duty varchar  true 
Maximum Price varchar  true 
Discount  varchar  true 
+1

你能否提供你到目前为止尝试过的代码,并让我们知道你遇到的问题? – Cristik

+0

[踢坏的习惯:选择错误的数据类型](http://sqlblog.com/blogs/aaron_bertrand/archive/2009/10/12/bad-habits-to-kick-using-the-wrong-data- type.aspx) - 你应该总是使用最合适的数据类型 - 毕竟这就是他们所在的地方!如果你有像'Price'或'Quantity'这样的列 - **不要**将它们存储为'varchar'!这是一个**可怕的糟糕的设计实践!** –

+0

对不起,我还没有做任何事,但我只是阅读教程,如果有可能@cristik 是啊我知道这里和thnks提醒我-marc 谢谢你俩comnt –

回答

0

您可以使用透视和“选择为”生成表。

或者,您可以使用T-SQL来写一个简短的脚本,并创建表你是这样的:

declare c cursor fast_forward for select colname from table_colname; 
declare @cname varchar(50), @sql varchar(1000); 
select @sql='create table table_fromcol (id int'; 
open c; 
fetch from c into @cname; 
while @@fetch_status=0 begin 
    select @[email protected] +','[email protected]+' varchar(50)'; 
    fetch next from c into @cname; 
end; 
select @[email protected]+')'; 
print @sql; 
exec(@sql); 
deallocate c; 

您可以编辑代码,以改变在新表中的列类型,大小。

相关问题