1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

ORDER BYのフィールドをCASE文で指定時でエラーが。

Posted at

SQLで質問があります。

sample01というテーブルに以下のデータが登録されています。

field01 | field02 | field03 | field04 | field05 | field06 | field07 | field08 | field09
10001 | test | 000 | 11 | 222 | 3 | 4444 | 55555 | 1234567
 ・
 ・
 ・

変数の値でORDER BYに指定するフィールドを制御しようとしていますが下記のエラーが出力されました。
「nvarchar の値 '0000000001100222000030444455555' の変換が int 型の列でオーバーフローしました。」

実行したSQLは以下の通りです。

declare @hensuu tinyint
set @hensuu = 3

select sub1.*
from (
  select
    field01 as sortfield01
    , field02 as sortfield02
    , cast(right('000000' + field03, 6) +
     right('00000' + field04, 5) +
     right('00000' + field05, 5) +
     right('00000' + field06, 5) +
     right('00000' + field07, 5) +
     right('00000' + field08, 5) as nvarchar(31)) as sortfield03
    , field09 as sortfield04
  from sample01
) as sub1
order by
  case when @hensuu = 1 then sub1.sortfield01
     when @hensuu = 2 then sub1.sortfield02
     when @hensuu = 3 then sub1.sortfield03
     when @hensuu = 4 then sub1.sortfield04
  end

何故、nvarchar型なのにint型に変換しようとしているのかわかりません。
どのようにすればエラーにならず、ORDER BYが実行できますでしょうか。
どうか、ご教授いただけませんでしょうか。
よろしくお願いします。

1
0
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?