Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HOW TO SELECT FROM EXEC sp_executeSql?

My stored procedures:

    @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

I want to

select * 
from EXEC SP_EXECUTESQL @Sql result 
where RowNum between (@currPage - 1) * @recodperpage + 1 
                 and @currPage * @recodperpage
like image 711
NamBui Avatar asked Feb 29 '16 16:02

NamBui


People also ask

What is EXEC sp_executesql in SQL?

What is the sp_executesql stored procedure? A SQL Server built-in stored procedures used to run one or multiple SQL statements stored within a string. This stored procedure allows executing static or strings built dynamically.

What is the difference between EXEC vs sp_executesql?

EXEC : EXEC/Execute is used to execute any stored procedure or character string. Mostly it is used to execute the stored procedure. 2. SP_ExecuteSQL: SP_ExecuteSQL is used to execute ad-hoc SQL statements so that they can be executed as parameterized statements.

Can we use sp_executesql in function?

It appears that you can't. You can execute extended stored procedure inside a function and, even though sp_executesql is an extended stored procedure (despite its name), it still generates the message "only functions and extended stored procedures can be executed within a function".


1 Answers

You can declare a @table with same columns as in stored procedure output and then:

INSERT INTO @table
EXEC SP_EXECUTESQL @Sql

SELECT *
FROM @table
where RowNum between (@currPage - 1) * @recodperpage + 1
                 and @currPage * @recodperpage
like image 187
gofr1 Avatar answered Oct 10 '22 20:10

gofr1