日期:2014-05-18  浏览次数:20536 次

动态sql语句使用匹配查询??
动态sql语句怎么样使用匹配查询?
SQL code

declare @store nvarchar(10)
declare stofile cursor  for
select distinct imsul_store from maxmast.imsul where imsul_store not like '%F' order by 1

open stofile

FETCH NEXT FROM stofile
INTO @store
WHILE @@FETCH_STATUS = 0 
begin

exec ('CREATE TABLE #'+@store+'
(
    [serno] [int] IDENTITY (1, 1)  NOT NULL ,
    [item] [nvarchar] (15) ,
    [store] [nvarchar] (10),
    [account] nvarchar(10),
    [bin] nvarchar(10),
    [qty] float 
) ON [PRIMARY]
INSERT INTO #'+@store+'
select imsul_item,imsul_store,imsul_account,imsul_bin,sum(imsul_balance) as qty from maxmast.imsul
where imsul_store like '''+@store+'%''
group by imsul_item, imsul_store,imsul_account,imsul_bin
order by imsul_bin


select * from #'+@store+'    
')

FETCH NEXT FROM stofile
INTO @store

end
close stofile
DEALLOCATE stofile


上面的代码哪出问题了,为什么我只能查出imsul_store=@store的记录,不能查出imsul_store =@store%的东西??

------解决方案--------------------
在游标中动态SQL?
试试

SQL code
exec ('CREATE TABLE #'+@store+'
(
    [serno] [int] IDENTITY (1, 1)  NOT NULL ,
    [item] [nvarchar] (15) ,
    [store] [nvarchar] (10),
    [account] nvarchar(10),
    [bin] nvarchar(10),
    [qty] float 
) ON [PRIMARY]
INSERT INTO #'+@store+'
select imsul_item,imsul_store,imsul_account,imsul_bin,sum(imsul_balance) as qty from maxmast.imsul
where imsul_store like '''+@store+'%'''
group by imsul_item, imsul_store,imsul_account,imsul_bin
order by imsul_bin


select * from #'+@store+')

------解决方案--------------------
'select imsul_item,imsul_store,imsul_account,imsul_bin,sum(imsul_balance) as qty from maxmast.imsul
where imsul_store like '''+@store+'%'''
你这只是查出以+@store开头的东西,确定你那两条数据是以+@store这个开头吗
------解决方案--------------------
SQL code
create table #
(
    [serno] [int] IDENTITY (1, 1)  NOT NULL ,
    [item] [nvarchar] (15) ,
    [store] [nvarchar] (10),
    [account] nvarchar(10),
    [bin] nvarchar(10),
    [qty] float 
)

declare @store nvarchar(10)
declare stofile cursor  for
select distinct imsul_store from maxmast.imsul where imsul_store not like '%F' order by 1

open stofile

FETCH NEXT FROM stofile
INTO @store
WHILE @@FETCH_STATUS = 0 
begin

truncate table #
/*print*/ exec ('INSERT INTO #
select imsul_item,imsul_store,imsul_account,imsul_bin,sum(imsul_balance) as qty from maxmast.imsul
where imsul_store like ''%'+@store+'%''
group by imsul_item, imsul_store,imsul_account,imsul_bin
order by imsul_bin')

select * from #

FETCH NEXT FROM stofile
INTO @store

end
close stofile
DEALLOCATE stofil