我有一个非常长的SQL语句,它具有以下框架(使用SQL Server 2005):
SELECT
a.something AS Something,
b.otherthing AS Otherthing,
(SELECT another FROM ... WHERE...) AS Importantvariable,
....
FROM...
INNER JOIN...
INNER JOIN...
WHERE a.columnname = (SELECT another FROM ... WHERE...) ....
这个Importantvariable
本身就是一个很长的查询。但是,它在同一查询的其他部分中使用,包括WHERE
子句和INNER JOIN
子句。我的问题是,我怎么能以某种方式保存它的价值,所以我不必每次都写出整个查询。在上面的示例中,我想键入a.columnname = Importantvariable
而不是整个查询。我尝试使用DECLARE
并将值保存在声明的变量中,但不允许我这样做,并出现以下错误:
A SELECT statement that assigns a value to a variable must not be combined with data-retrieval operation.
当然,这是有道理的,但我的重点是执行数据检索,我只是不想复制和粘贴在查询中的几个不同位置定义Importantvariable
的非常长的查询。
有什么想法吗?
答案 0 :(得分:3)
您可以使用APPLY
创建类似命名变量 row-wise 的内容。如果值计算一次并且对整个集合有效(更像是常量),则可以使用CTE
(从WITH
之前的SELECT
开始。)
以下内容将使用APPLY
查找所有列的表名。您可以在列列表以及The.ImportantVariable
- 子句中使用WHERE
:
SELECT The.ImportantVariable
,c.*
FROM sys.columns AS c
OUTER APPLY(SELECT name FROM sys.objects AS o WHERE c.object_id=o.object_id) AS The(ImportantVariable)
WHERE The.ImportantVariable LIKE 'a%';
检查一下! CTE提供的 1行中有一些常量值,您可以CROSS JOIN
进入查询并用作命名常量
WITH SomeConstants AS
(
SELECT 'I''m a constant value' AS Constant1 --might be a complex statement too!
,0 AS Constant2
)
SELECT The.ImportantVariable
,Constant1
,Constant2
,c.*
FROM SomeConstants
CROSS JOIN sys.columns AS c
OUTER APPLY(SELECT name FROM sys.objects AS o WHERE c.object_id=o.object_id) AS The(ImportantVariable)
WHERE The.ImportantVariable LIKE 'a%'
答案 1 :(得分:0)
您正在寻找的是Microsoft SQL Server的公用表格式(CTE)
你可以在这里阅读它们: https://technet.microsoft.com/en-us/library/ms190766(v=sql.105).aspx
你做的是
WITH (columns)
AS (query)
SELECT (another query using (possibly many times) the previous query)
答案 2 :(得分:0)
听起来你正在寻找一个视图。视图本质上是一个存储的SQL语句,可以像表名一样调用。
SELECT * FROM view_name ... WHERE ...
通常,视图包含许多带有别名的连接和列,允许您创建虚拟对象,而无需跨多个SQL表复制数据。
查看您的文档以了解具体信息,但这里是W3schools示例的链接 Click to open image
答案 3 :(得分:0)
使用外部或交叉应用。它使您的查询更易读,也可能更快。
SELECT
a.something AS Something,
b.otherthing AS Otherthing,
Importantvariable,
....
FROM...
INNER JOIN...
INNER JOIN...
outer apply (SELECT another AS Importantvariable FROM ... WHERE...)
WHERE a.columnname = Importantvariable ....
答案 4 :(得分:0)
我建议像这样使用CTE:
;with cte as
(
SELECT
a.something AS Something,
b.otherthing AS Otherthing,
(SELECT another FROM ... WHERE...) AS Importantvariable,
....
FROM...
INNER JOIN...
INNER JOIN...
)
select *,
<maybe more uses of Importantvariable>
from cte
WHERE columnname = Importantvariable;