将Oracle解码语句转换为SQL Server T-SQL语句

时间:2017-01-23 21:21:05

标签: sql sql-server case decode

当不再使用oracle数据库时,我们的重点是将所有查询语句从Oracle转换为SQL Server(T-SQL)语句。我在解决Decode问题时遇到了一些问题,下面的一行我一直试图改变它但是当我在sql server中运行它进行测试时它会给我一些错误。

Dim query As String = "SELECT DocType, 
docyear, 
docmonth, 
DECODE(docmonth, NULL, NULL, '0', '- All Months -', TO_CHAR(TO_DATE(docmonth||'/01/2008', 'MM/DD/YYYY'), 'docmonth')) 
monthAlpha, 
DID 
from dbo.Document where XALASKAID = '" & LicenseNumber & "' and DOCTYPE like '%Report%'"

但是这条解码线导致错误。

2 个答案:

答案 0 :(得分:0)

1

使用Oracle的专有功能( DECODE TO_CHAR TO_DATE )甚至连接运算符( || )在SQL Server中不会让你走得太远。

2

case ... when null无效。

e.g。

declare @t table (i int)
insert into @t (i) values (null)
select case i when null then 1 else 2 end as x from @t
+---+
| x |
+---+
| 2 |
+---+

而不是

case x when null then ... when y then ... when z then .. else ... end

你必须使用

case when x is null then ... when x = y then ... when x = z then ... else ... end

答案 1 :(得分:0)

你能尝试一下CASE声明吗?

Dim query As String = "
SELECT
docType, 
docyear, 
docmonth, 
TO_CHAR(TO_DATE(docmonth||'/01/2008', 'MM/DD/YYYY'), 'docmonth')) 
CASE
  WHEN docmonth IS NULL THEN NULL
  WHEN docmonth = '0' THEN '- All Months -'
  WHEN docmonth >= AND docmonth <= 12 THEN DATENAME(month, DATEADD(month, docmonth, -1))
END CaseDocMonth,
monthAlpha, 
DID 
FROM dbo.Document
WHERE XALASKAID = '" & LicenseNumber & "'
AND DOCTYPE like '%Report%';"

written about DECODE before,CASE通常是首选,因为它更易于阅读,并且具有更大的灵活性。