我的表格包含以下列:
int ID
(身份)BusinessFilterPhrase nvarchar(50)
BusinessCategoryID int
想要插入一条记录'已经'只有在没有记录的情况下才能使用'。下面的语句插入多个记录取决于有多少记录没有'。因此,如果我的表格中没有数据记录,那就是'表格中有3条记录,它将插入3条记录,其中包含新数据'我很困惑。
insert into tblBusinessName(BusinessFilterPhrase, BusinessCategoryID)
select 'been', 4
from tblBusinessName t1
where NOT EXISTS (select 1
from tblBusinessName d1
where d1.BusinessFilterPhrase = 'been'
)
似乎在第一个选择作品中插入了前1名。没有在表中创建BuisnessFilterPhrase Unique的任何其他方法吗?
insert into tblBusinessName(BusinessFilterPhrase, BusinessCategoryID)
select top 1 'been', 4
from tblBusinessName t1
where NOT EXISTS (select 1
from tblBusinessName d1
where d1.BusinessFilterPhrase = 'been'
)
如果您的表格为空白,则发现此声明不会插入任何内容。注意选择前1。
答案 0 :(得分:0)
根本不要从表格中选择:
insert into tblBusinessName(BusinessFilterPhrase, BusinessCategoryID)
select 'been', 4
where not exists (select * from tblBusinessName where BusinessFilterPhrase = 'been')
或者:
if not exists (select * from tblBusinessName where BusinessFilterPhrase = 'been')
begin
insert into tblBusinessName(BusinessFilterPhrase, BusinessCategoryID)
select 'been', 4
end