creating a SQL table with multiple columns automatically

↘锁芯ラ 提交于 2019-12-25 05:48:09

问题


I must create an SQL table with 90+ fields, the majority of them are bit fields like N01, N02, N03 ... N89, N90 is there a fast way of creating multiple fileds or is it possible to have one single field to contain an array of values true/false? I need a solution that can also easily be queried.


回答1:


At least you can generate ALTER TABLE scripts for bit fields, and then run those scripts.

DECLARE @COUNTER INT = 1
WHILE @COUNTER < 10
BEGIN
    PRINT 'ALTER TABLE table_name ADD N' + RIGHT('00' + CONVERT(NVARCHAR(4), @COUNTER), 2) + ' bit'
    SET @COUNTER += 1
END



回答2:


There is no easy way to do this and it will be very challenging to do queries against such a table. Create a table with three columns - item number, bit field number and a value field. Then you will be able to write 'good' succinct Tsql queries against the table.




回答3:


TLDR: Use binary arithmetic.

For a structure like this

==============
Table_Original
==============
Id | N01| N02 |...

I would recommend an alternate table structure like this

==============
Table_Alternate
==============
Id | One_Col

This One_Col is of varchar type which will have value set as

cast(n01 as nvarchar(1)) + cast(n02 as nvarchar(1))+ cast(n03 as nvarchar(1)) as One_Col

I however feel that you'd use C# or some other programming language to set value into column. You can also use bit and bit-shift operations.

Whenever you need to get a value, you can use SQL or C# syntax(treating as string) In sql query terms you can use a query like

SELECT SUBSTRING(one_col,@pos,1) 

and @pos can be set like

DECLARE @Colname nvarchar(4)
SET @colname=N'N32'
 --    ....
SET @pos= CAST(REPLACE(@colname,'N','') as INT)

Also you can use binary arithmetic too with ease in any programming language.




回答4:


Use three columns.

Table
ID         NUMBER,
FIELD_NAME VARCHAR2(10),
VALUE      NUMBER(1)

Example

ID FIELD        VALUE
1    N01        1
1    N02        0
.
1    N90        1
.
2    N01        0
2    N02        1
.
2    N90        1
.

You can also OR an entire column for a fieldname (or fieldnameS):

select DECODE(SUM(VALUE), 0, 0, 1) from table where field_name = 'N01';

And even perform an AND

select EXP(SUM(LN(VALUE))) from table where field_name = 'N01';

(see http://viralpatel.net/blogs/row-data-multiplication-in-oracle/)


来源:https://stackoverflow.com/questions/32072690/creating-a-sql-table-with-multiple-columns-automatically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!