数据定义语言(DDL)查询SQL

时间:2018-10-31 19:30:07

标签: sql sql-server ddl

我是查询和SQL Server的新手,我想了解DDL。 我的表格中有一个属性,该属性具有多个值,例如 大小= {'S','M','L'}。 我如何通过查询在表中创建属性,以便可以将多个值插入到属性之一?

2 个答案:

答案 0 :(得分:0)

您不想这样做,因为这会使您的数据不规范。但是,如果必须的话。

declare @table table (id int identity(1,1),  size varchar(16))

insert into @table
values
('S')
,('M')

select * from @table

update @table
set size = size + ',M'
where id = 1

select * from @table

这里是带有外键的一对多方法

create table #items (id int identity(1,1), descrip varchar(64))

insert into #items
values
('shirt'),
('pants')

create table #item_sizes (id int identity(1,1), size char(1), item_id int)
alter table #item_sizes
add constraint FK_item foreign key (item_id) references #items(id)

insert into #item_sizes
values
('S',1)
,('M',1)
,('L',1)
,('S',2)

select 
    ItemID = i.id
    ,i.descrip
    ,isiz.size
from #items i
inner join #item_sizes isiz
on isiz.item_id = i.id


drop table #items, #item_sizes

答案 1 :(得分:0)

根据您的要求:

产品(...,ProductSize);

 INSERT INTO Product (ProductSize) VALUES ('S')

如何查询ProductSize的行,以便可以在SQL中插入多个值? –

您可以如下查询

 select * from Product where ProductSize like '%S%' or ProductSize like '%L%' or ProductSize like '%M%'