自己寫了一個遊標查詢多條件的sql語句
DECLARE
@s
CHAR
(
200
)
Declare @where varchar ( 200 )
Declare @col char ( 10 )
Declare @sql varchar ( 200 )
Set @col = ' col013 '
set @where = ''
set @sql = ''
SET @s = ' 14 11 '
Declare @str varchar ( 100 )
Declare my_cur Cursor
For SELECT ' , ' + a + ' , ' k FROM dbo.Split( @s , ' ' )
OPEN my_cur
FETCH NEXT FROM my_cur into @str
WHILE @@FETCH_STATUS = 0
Begin
-- SELECT col001,col013 FROM d_table_2 where ','+col013+',' like '%'+@str+'%'
Set @where = @where + dbo.trim( @col ) + ' like ' + ''' % ' + @str + ' % ''' + ' and '
-- Set @where = 'tet'
FETCH NEXT FROM my_cur into @str
end
set @where = left ( @where , len ( @where ) - 4 )
-- select @where
set @sql = N ' SELECT col001,col013 FROM d_table_2 where ' + @where
-- select @sql
exec ( @sql )
CLOSE my_cur
DEALLOCATE my_cur
-- ------------------
不用遊標方式
Declare @fields VARCHAR ( 1024 )
select @fields = dbo.trim( isnull ( @fields , '' )) + ' , ' + k
from (( select top 10 id as k from part)) as a
select @fields
CREATE Function Split( @Sql varchar ( 8000 ), @Splits varchar ( 10 )) -- 此函數是別人寫的
returns @temp Table (a varchar ( 100 ))
As
Begin
Declare @i Int
Set @Sql = RTrim ( LTrim ( @Sql ))
Set @i = CharIndex ( @Splits , @Sql )
While @i >= 1
Begin
Insert @temp Values ( Left ( @Sql , @i - 1 ))
Set @Sql = SubString ( @Sql , @i + 1 , Len ( @Sql ) - @i )
Set @i = CharIndex ( @Splits , @Sql )
End
Declare @where varchar ( 200 )
Declare @col char ( 10 )
Declare @sql varchar ( 200 )
Set @col = ' col013 '
set @where = ''
set @sql = ''
SET @s = ' 14 11 '
Declare @str varchar ( 100 )
Declare my_cur Cursor
For SELECT ' , ' + a + ' , ' k FROM dbo.Split( @s , ' ' )
OPEN my_cur
FETCH NEXT FROM my_cur into @str
WHILE @@FETCH_STATUS = 0
Begin
-- SELECT col001,col013 FROM d_table_2 where ','+col013+',' like '%'+@str+'%'
Set @where = @where + dbo.trim( @col ) + ' like ' + ''' % ' + @str + ' % ''' + ' and '
-- Set @where = 'tet'
FETCH NEXT FROM my_cur into @str
end
set @where = left ( @where , len ( @where ) - 4 )
-- select @where
set @sql = N ' SELECT col001,col013 FROM d_table_2 where ' + @where
-- select @sql
exec ( @sql )
CLOSE my_cur
DEALLOCATE my_cur
-- ------------------
不用遊標方式
Declare @fields VARCHAR ( 1024 )
select @fields = dbo.trim( isnull ( @fields , '' )) + ' , ' + k
from (( select top 10 id as k from part)) as a
select @fields
CREATE Function Split( @Sql varchar ( 8000 ), @Splits varchar ( 10 )) -- 此函數是別人寫的
returns @temp Table (a varchar ( 100 ))
As
Begin
Declare @i Int
Set @Sql = RTrim ( LTrim ( @Sql ))
Set @i = CharIndex ( @Splits , @Sql )
While @i >= 1
Begin
Insert @temp Values ( Left ( @Sql , @i - 1 ))
Set @Sql = SubString ( @Sql , @i + 1 , Len ( @Sql ) - @i )
Set @i = CharIndex ( @Splits , @Sql )
End