如何从EXEC sp_executeSql中选择?

时间:2016-02-29 16:28:26

标签: sql-server tsql

我的存储过程:

    @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

2 个答案:

答案 0 :(得分:3)

您可以使用与过程输出相同的列声明@table。比:

INSERT INTO @table
EXEC SP_EXECUTESQL @Sql

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

答案 1 :(得分: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 =@currPage,
  @recodperpage =@recodperpage