我正在为初始页面加载创建存储过程,因此有两个不同的查询和结果集。
第一个查询在第二个查询中完全重复为嵌套SELECT
。
我的问题是,是将第一个查询的结果放入表格var还是只是在第二个查询中复制代码/查询?
提前致谢。
--Get Most Popular Sports for each country
SELECT
dbo.Countries2Sports.rank,
dbo.Countries2Sports.SportName,
dbo.Countries2Sports.imageURL,
dbo.Countries2Sports.imageALTtext
FROM
dbo.Countries2Sports
WHERE
dbo.Countries2Sports.CountryCode = @CountryCode
ORDER BY
dbo.Countries2Sports.rank ASC
--Get Organizations related to each country's sports
SELECT
dbo.Countries2Organizations.ID,
dbo.Countries2Organizations.OrganizationCode,
dbo.Countries2Organizations.OrganizationName,
dbo.Countries2Organizations.LogoURL,
dbo.Countries2Organizations.Sport
FROM
dbo.Countries2Organizations
WHERE
dbo.Countries2Organizations.Sport IN
(
SELECT
dbo.Countries2Sports.SportName
FROM
dbo.Countries2Sports
WHERE
dbo.Countries2Sports.CountryCode = @CountryCode
)
AND (dbo.Countries2Organizations.CountryCode = @CountryCode OR
dbo.Countries2Organizations.CountryCode = '')
答案 0 :(得分:3)
如果您不想在输出中使用结果集,那么您可以使用CTE,如果记录数量低,则可以比临时表更好:
;WITH CTE AS (
SELECT
dbo.Countries2Sports.rank,
dbo.Countries2Sports.SportName,
dbo.Countries2Sports.imageURL,
dbo.Countries2Sports.imageALTtext
FROM
dbo.Countries2Sports
WHERE
dbo.Countries2Sports.CountryCode = @CountryCode
--ORDER BY
-- dbo.Countries2Sports.rank ASC
)
--Get Organizations related to each country's sports
SELECT
dbo.Countries2Organizations.ID,
dbo.Countries2Organizations.OrganizationCode,
dbo.Countries2Organizations.OrganizationName,
dbo.Countries2Organizations.LogoURL,
dbo.Countries2Organizations.Sport
FROM
dbo.Countries2Organizations
WHERE
dbo.Countries2Organizations.Sport IN
(
SELECT
dbo.Countries2Sports.SportName
FROM
CTE
)
AND ( dbo.Countries2Organizations.CountryCode = @CountryCode OR dbo.Countries2Organizations.CountryCode = '')