首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 数据库 > SQL Server >

SQL中能实现这种查询吗?该怎么处理

2012-01-19 
SQL中能实现这种查询吗?SQL code一般我们用SQL模糊查询是这样的例如从字段str中选择带有key的记录SELECT *

SQL中能实现这种查询吗?

SQL code
一般我们用SQL模糊查询是这样的例如从字段str中选择带有key的记录SELECT * FROM TABLE1WHERE str like '%key%'字段str在key中高手们怎么实现?例如有一记录中str为"abc"而查找关键词为"fgabcde"我想找到str为abc的这条记录该怎么样写呢?


[解决办法]
SQL code
declare @T table(str nvarchar(10))insert @T select 'saKeybcc'insert @T select 'Keybcc'insert @T select 'Key'SELECT * FROM @T WHERE str like '%_key_%'--加一个"_",key前后最少要有一个字符select * from @T where Str like 'key'--或select * from @T where Str= 'key'str        ---------- saKeybcc(所影响的行数为 1 行)str        ---------- Key(所影响的行数为 1 行)str        ---------- Key(所影响的行数为 1 行)
[解决办法]
SQL code
declare @T table(str nvarchar(10))insert @T select 'abc'insert @T select 'fga'insert @T select 'Key'select * from @t where PATINDEX('%'+str+'%' , 'fgabcde')>0
[解决办法]
SQL code
create table #tab1(id1 int null,id2 int null,id3 int null) goinsert into #tab1(id1,id2,id3)select id1,id2,id3 from (    select 1 as id1,1 as id2,1 as id3 union     select 1,2,3 ) as tabgocreate table #tab(id1 int null,id2 int null,id3 int null)godeclare @id1 int declare curst cursor static forselect id1 from #tab1 group by id1open curstfetch next from curst into @id1while @@fetch_status = 0 begin    insert #tab(id1,id2,id3) select top 1 id1,id2,id3 from #tab1    fetch next from curst into @id1endclose curstdeallocate curstselect * from #tabgodrop table #tab1drop table #tabgo table #tab1(id1 int null,id2 int null,id3 int null) goinsert into #tab1(id1,id2,id3)select id1,id2,id3 from (    select 1 as id1,1 as id2,1 as id3 union     select 1,2,3 ) as tabgocreate table #tab(id1 int null,id2 int null,id3 int null)godeclare @id1 int declare curst cursor static forselect id1 from #tab1 group by id1open curstfetch next from curst into @id1while @@fetch_status = 0 begin    insert #tab(id1,id2,id3) select top 1 id1,id2,id3 from #tab1    fetch next from curst into @id1endclose curstdeallocate curstselect * from #tabgodrop table #tab1drop table #tabgo,id3 from (    select 1 as id1,1 as id2,1 as id3 union     select 1,2,3 ) as tabgocreate table #tab(id1 int null,id2 int null,id3 int null)godeclare @id1 int declare curst cursor static forselect id1 from #tab1 group by id1open curstfetch next from curst into @id1while @@fetch_status = 0 begin    insert #tab(id1,id2,id3) select top 1 id1,id2,id3 from #tab1    fetch next from curst into @id1endclose curstdeallocate curstselect * from #tabgodrop table #tab1drop table #tabgo 

热点排行