0

Mysql プロシージャに変換したい MSsql プロシージャがありますが、mysql で「CTE」式を変換する方法がわかりません。

以下に、関連する手順を掲載しています。

  WITH    CTE
              AS ( SELECT   ROW_NUMBER() OVER ( ORDER BY CASE
                                                          WHEN @SortColumnName = 'UserID'
                                                          AND @SortOrderBy = 'asc'
                                                          THEN UserID
                                                         END ASC, CASE
                                                          WHEN @SortColumnName = 'UserID'
                                                          AND @SortOrderBy = 'desc'
                                                          THEN UserID
                                                          END DESC) AS RN ,
                            UserID ,
                            UserName ,
                            FirstName ,
                            MiddleName ,
                            LastName ,
                            EmailID
                   FROM     [Users]
                 )
4

2 に答える 2

0

次の代わりに、サブクエリに変更できます。

;with cte as
(
    select column
      from table
)
select *
  from cte

あなたは書ける:

select *
  from (select column
          from table) as cte
于 2013-01-23T07:37:06.410 に答える
0

What you need to use is a Derived Table, as you are using the ranking function Row_Number and obviously you would need to refer to it in your WHERE clause now.

MySQL supports derived tables and the performance between CTE and derived tables in SQL is the same, they are both Table Expressions.

Your new code will look something like this: (depending on your need that is not tabled above)

SELECT *
FROM
    (SELECT ROW_NUMBER() OVER (
        ORDER BY 
         CASE WHEN @SortColumnName = 'UserID' AND @SortOrderBy = 'asc' THEN UserID END ASC, 
         CASE WHEN @SortColumnName = 'UserID' AND @SortOrderBy = 'desc' THEN UserID END DESC
    ) AS RN,
      UserID ,
      UserName ,
      FirstName ,
      MiddleName ,
      LastName ,
      EmailID
     FROM     [Users]
 ) DTABLE
WHERE DTABLE.RN = 1;

But this just deals with your question on the CTE.

Row_Number is not available in MySQL as noted above, but check this page for answers on that part: ROW_NUMBER() in MySQL

EDIT: New Example dropping the Row_Number by and making use of LIMIT:

(As stated below, there is a simpler way to accomplish changeble sorting and getting spesific rows, See below query.)

SELECT
      UserID ,
      UserName ,
      FirstName ,
      MiddleName ,
      LastName ,
      EmailID
FROM     
    [Users]
ORDER BY 
         CASE WHEN @SortColumnName = 'UserID' AND @SortOrderBy = 'asc' THEN UserID END ASC, 
         CASE WHEN @SortColumnName = 'UserID' AND @SortOrderBy = 'desc' THEN UserID END DESC END
LIMIT 1,1
于 2013-01-23T07:56:29.407 に答える