运行SQL Server存储过程(更新)

时间:2017-10-17 13:30:24

标签: sql-server tsql stored-procedures

当我想在SQL Server中运行以下查询时,我收到以下2个错误 - 我该如何解决错误?你能救我吗?

运行:

exec [dbo].[sp_siparisTest] 0,25,'','',''

错误:

第15行,第15行,第1行,第53行 关键字“ORDER”附近的语法不正确。

Msg 102,Level 15,State 1,Line 53 '25'附近的语法不正确。

ALTER PROC [dbo].[sp_siparisTest]
(
  @PageNo INT,
  @RowCountPerPage INT,
  @adsoyadfilter NVARCHAR(50),
  @odemetip NVARCHAR(20),
  @durumu NVARCHAR(20)
)
AS
BEGIN
DECLARE @devam_ nvarchar(max)
SET @devam_ ='SELECT
u.AdiSoyadi as AdSoyad,
ot.Adi as OdemeTipAdi,
sd.Adi as SiparisDurumAdi,
s.OlusturmaTarihi as OlusturmaTarihi,
s.GenelToplam as GenelToplam
FROM
	Siparis as s with(NOLOCK)
inner join 
	SiparisDurum as sd with(NOLOCK) on s.Durumu=sd.Id
inner join 
	Uye as u with(NOLOCK) on s.Uye_Id=u.Id
inner join
	OdemeTip as ot with(NOLOCK) on s.OdemeTip=ot.Id  where '	
IF(@adsoyadfilter !='') 
	SET @devam_ += '(u.AdiSoyadi LIKE ''%'' + '+ @adsoyadfilter +' + ''%'') AND'
IF(@odemetip != '') 
	SET @devam_ += ' ot.Id IN(SELECT Value FROM fn_Split( '+ @odemetip +' , '','')) AND'
IF(@odemetip != '')
	SET @devam_ += ' s.Durumu IN(SELECT Value FROM fn_Split( '+@durumu +','',''))'
SET @devam_ +=' ORDER BY s.Id OFFSET (' + cast(@PageNo as nvarchar(255)) + ')  ROWS FETCH NEXT (' + cast(@RowCountPerPage as nvarchar(255)) + ') ROWS ONLY'
END

EXECUTE sp_executesql @devam_

2 个答案:

答案 0 :(得分:1)

在倒数第二行,将SET更改为:

SET @devam_ +=' ORDER BY s.Id OFFSET (' + cast(@PageNo as varchar(64)) + ')  ROWS FETCH NEXT (' + cast(@RowCountPerPage as varchar(64)) + ') ROWS ONLY)'

答案 1 :(得分:1)

如果所有参数都是'那么你需要一个条款。 (1 = 1)并在字符串之外取@RowCountPerPage:

ALTER PROC sp_siparisTest
(
  @PageNo INT,
  @RowCountPerPage INT,
  @adsoyadfilter NVARCHAR(50),
  @odemetip NVARCHAR(20),
  @durumu NVARCHAR(20)
)
AS
BEGIN
DECLARE @devam_ nvarchar(max)
SET @devam_ = 'SELECT
u.AdiSoyadi as AdSoyad,
ot.Adi as OdemeTipAdi,
sd.Adi as SiparisDurumAdi,
s.OlusturmaTarihi as OlusturmaTarihi,
s.GenelToplam as GenelToplam
FROM
    Siparis as s with(NOLOCK)
inner join 
    SiparisDurum as sd with(NOLOCK) on s.Durumu=sd.Id
inner join 
    Uye as u with(NOLOCK) on s.Uye_Id=u.Id
inner join
    OdemeTip as ot with(NOLOCK) on s.OdemeTip=ot.Id  where( '

IF(@adsoyadfilter !='') 
    SET @devam_ += '(u.AdiSoyadi LIKE ''%'' + @adsoyadfilter + ''%'') AND'
IF(@odemetip != '') 
    SET @devam_ += ' ot.Id IN(SELECT Value FROM fn_Split(@odemetip, '','')) AND'
IF(@odemetip != '')
    SET @devam_ += ' AND s.Durumu IN(SELECT Value FROM fn_Split(@durumu,'','')) '

if @adsoyadfilter + @odemetip + @odemetip = '' SET @devam_ += '1=1) '

SET @devam_ +=' ORDER BY s.Id OFFSET (' + cast(@PageNo as nvarchar(255)) + ')  ROWS FETCH NEXT (' + cast(@RowCountPerPage as nvarchar(255)) + ') ROWS ONLY'
END

EXECUTE sp_executesql @devam_