0

我几乎已经用 Sql Server 替换了我们的应用程序后端,但遇到了一个问题。以下 Access 查询不适用于 Sql Server。

SELECT table1.*
FROM   table1
       INNER JOIN (table2
                   INNER JOIN table3
                           ON ( table2.custkey = table3.custkey )
                              AND ( table2.sequence = table3.sequence ))
               ON table1.account = table2.account
WHERE  (( LEFT(table2.keyid, 1) = 'B' ))
ORDER  BY table3.lastname & table3.firstname,
          table1.account; 

我已经尝试了该语句的多种变体,但未能使其发挥作用。此声明的一些帮助将帮助我修改其他一些。任何帮助,将不胜感激。

4

2 回答 2

2

唯一突出的是SQL Server 中的“ &” 。+但是,在访问中也将 NULL 值视为空字符串,这需要在 SQL Server 中&进一步处理:ISNULL

SELECT table1.*
FROM   table1
       INNER JOIN (table2
                   INNER JOIN table3
                           ON ( table2.custkey = table3.custkey )
                              AND ( table2.sequence = table3.sequence ))
               ON table1.account = table2.account
WHERE  (( LEFT(table2.keyid, 1) = 'B' ))
ORDER  BY isnull(table3.lastname,'') + isnull(table3.firstname,''),
          table1.account; 

如果我要从头开始在 SQL Server 中编写查询,我可能会顺序执行连接,而不是在连接回 t1 之前在括号中执行 t2-t3。第一个字符的测试也将表示为 LIKE(个人偏好)。

  SELECT table1.*
    FROM table1
    JOIN table2 ON table1.account = table2.account
    JOIN table3 ON table2.custkey = table3.custkey AND table2.sequence = table3.sequence
   WHERE table2.keyid LIKE 'B%'
ORDER BY isnull(table3.lastname,'') + isnull(table3.firstname,''), table1.account;
于 2012-11-29T00:38:17.000 回答
1
SELECT table1.*
FROM   table1
INNER JOIN table2  ON table1.account = table2.account
INNER JOIN table3  ON ( table2.custkey = table3.custkey ) 
                      AND ( table2.sequence = table3.sequence )
WHERE  LEFT(table2.keyid, 1) = 'B' 
ORDER  BY table3.lastname, table3.firstname, table1.account; 

如果您希望 where 子句适用于索引,请使用 LIKE 重写:

SELECT table1.*
FROM   table1
INNER JOIN table2  ON table1.account = table2.account
INNER JOIN table3  ON ( table2.custkey = table3.custkey ) 
                      AND ( table2.sequence = table3.sequence )
WHERE  table2.keyid LIKE 'B%' 
ORDER  BY table3.lastname, table3.firstname, table1.account; 
于 2012-11-29T00:37:32.563 回答