Question

I'm trying to one sql query

alter procedure [dbo].[sp_E_GetProducts]
@skip as INT = 0,
@take as INT = 999999,
@search as NVARCHAR(50) = '',
@urtkod as NVARCHAR(50) = ''
as
begin
; with MyTable as ( 
select sto_kod, sto_isim, sto_sat_cari_kod, ROW_NUMBER() OVER (ORDER BY sto_kod) as row from MikroDB_V14_AKCAY2010.dbo.STOKLAR where
(sto_isim like '%' + @search + '%' or sto_kod like '%' + @search + '%') and sto_sat_cari_kod <> '' and  @urtkod like '%' + sto_sat_cari_kod + '%'

)

select * from MyTable where row between @skip and @take
end

its working when i put parameters not null but when @urtkod is null i want take all table (it mean "and sto_sat_cari_kod <> '' and @urtkod like '%' + sto_sat_cari_kod + '%'" will ignore), i research "case when" but it didn't work or i do it wrong.

Was it helpful?

Solution

alter procedure [dbo].[sp_E_GetProducts]
@skip as INT = 0,
@take as INT = 999999,
@search as NVARCHAR(50) = '',
@urtkod as NVARCHAR(50) = ''
as
begin
    If (@urtkod is null)
    Begin
        ; with MyTable as ( 
        select sto_kod, sto_isim, sto_sat_cari_kod, ROW_NUMBER() OVER (ORDER BY sto_kod) as row from MikroDB_V14_AKCAY2010.dbo.STOKLAR where
        (sto_isim like '%' + @search + '%' or sto_kod like '%' + @search + '%') and sto_sat_cari_kod <> '' and  @urtkod like '%' + sto_sat_cari_kod + '%'

        )
    End
    Else
    Begin
        ; with MyTable as ( 
        select sto_kod, sto_isim, sto_sat_cari_kod, ROW_NUMBER() OVER (ORDER BY sto_kod) as row from MikroDB_V14_AKCAY2010.dbo.STOKLAR where
        (sto_isim like '%' + @search + '%' or sto_kod like '%' + @search + '%') and sto_sat_cari_kod <> '' --and  @urtkod like '%' + sto_sat_cari_kod + '%'

        )
    End
select * from MyTable where row between @skip and @take
end

Also you can check for ''....

OTHER TIPS

Change the below section

and  @urtkod like '%' + sto_sat_cari_kod + '%'

to

and     (@urtkod like '%' + sto_sat_cari_kod + '%' OR @urtkod IS NULL)

Using SQL SERVER and ISNULL

you could change it to

and     (ISNULL(@urtkod,'') like '%' + sto_sat_cari_kod + '%')

Also maybe have a look at SQL NULL Functions for the different version between RDBMSs

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top