2016-02-29 51 views
3

我的存儲過程:如何從EXEC sp_executeSql中選擇?

@currPage int, 
    @recodperpage int, 
    @name varchar(20) = NULL, 
    @type varchar(50) = NULL, 
    @size varchar(50) = NULL, 
    @country varchar(50) = NULL 
AS 
BEGIN 
    DECLARE @Sql NVARCHAR(MAX); 

    SELECT 
     @Sql = N'SELECT ROW_NUMBER() 
      OVER(ORDER BY MatchID Desc) AS RowNum, 
      MatchID, 
      NameMatch, 
      Images 
     FROM Match WHERE MatchID > 0 ' 

    IF @type IS NOT NULL 
     SELECT @Sql += N' AND Type = ''' + REPLACE(convert(varchar(50),@type),'''','''''')+''''; 

    IF @size IS NOT NULL 
     SELECT @Sql += N' AND MatchSize = ''' + REPLACE(convert(varchar(50),@size),'''','''''')+''''; 

    IF @country IS NOT NULL 
     SELECT @Sql += N' AND Country = ''' + REPLACE(convert(varchar(50),@country),'''','''''')+'''' 

    EXEC SP_EXECUTESQL @Sql 
END 

我想

select * 
from EXEC SP_EXECUTESQL @Sql result 
where RowNum between (@currPage - 1) * @recodperpage + 1 
       and @currPage * @recodperpage 
+0

http://stackoverflow.com/questions/35428540/insert-into-table-the-result-from-存儲過程加額外列/ 35429174#35429174 –

回答

3

你可以聲明與相同的列程序輸出@table。比:

INSERT INTO @table 
EXEC SP_EXECUTESQL @Sql 

SELECT * 
FROM @table 
where RowNum between (@currPage - 1) * @recodperpage + 1 
       and @currPage * @recodperpage 
2

我想你可以參數化的where子句中動態查詢

DECLARE @Sql   NVARCHAR(MAX), 
     @currPage  INT, 
     @recodperpage INT 

SELECT @Sql = N'select * from(SELECT ROW_NUMBER() 
      OVER(ORDER BY MatchID Desc) AS RowNum, 
      MatchID, 
      NameMatch, 
      Images 
     FROM Match WHERE MatchID > 0 ' 

IF @type IS NOT NULL 
    SELECT @Sql += N' AND Type = ''' 
       + Replace(CONVERT(VARCHAR(50), @type), '''', '''''') 
       + ''''; 

IF @size IS NOT NULL 
    SELECT @Sql += N' AND MatchSize = ''' 
       + Replace(CONVERT(VARCHAR(50), @size), '''', '''''') 
       + ''''; 

IF @country IS NOT NULL 
    SELECT @Sql += N' AND Country = ''' 
       + Replace(CONVERT(VARCHAR(50), @country), '''', '''''') 
       + '''' 

SELECT @sql += ') A where RowNum between (@currPage - 1) * @recodperpage + 1 
       and @currPage * @recodperpage' 

EXEC Sp_executesql 
    @Sql, 
    N'@currPage int,@recodperpage int', 
    @currPage [email protected], 
    @recodperpage [email protected]