2012-11-29 51 views
0

我几乎已经完成了用Sql Server替换我们的应用程序,但是我遇到了一个问题。以下Access查询不适用于Sql Server。如何使此SQL语句与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; 

我试过这个声明的多种变体,但一直没能得到它的工作。这个声明的一些帮助将帮助我修改其他几个人。任何帮助,将不胜感激。

+0

另一个评论。在您的ORDER BY上,您正在对派生字段进行排序(即姓氏+名字)。这将使数据库引擎首先组合这两个字段,并对非索引结果进行排序。 你可以改为做一个ORDER BY table3.lastname,table3.firstname, table1.account 这会给你相同的结果,但速度更快。 –

回答

2

那伸出的唯一的事情就是“&”,这是在SQL Server +。然而,&在访问也将NULL值视为空字符串,这需要与ISNULL在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 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; 
+0

感谢您的回复,我做了这些改变,现在它工作正常。这是“&”,我不得不把这个改变为+几次,这是我的注意力。再次感谢。 –

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;