在SQL Server中创建并执行存储过程

时间:2016-12-19 13:13:00

标签: sql-server tsql stored-procedures

我有四张桌子:

  • dbo.Projects(id,ProjectName,Areas,PaymentSystem,Districts.id,purpose.id,types.id等)
  • dbo.Districts(id,DistrictsName)
  • dbo.Purpose(id,PurposeName) - 有住宅&商业
  • dbo.Types(id,typName)

我想选择DispectsName,其中PurposeName =' residential'

我尝试了这个程序:

CREATE PROCEDURE [dbo].[SearchResidentialProjects]   
AS
SELECT 
    dbo.Projects.ID,
    dbo.Districts.DistrictName,
    dbo.Purpose.PurposeName
FROM 
    dbo.Projects 
INNER JOIN 
    dbo.Purpose ON dbo.Projects.PurposeID = dbo.Purpose.ID 
INNER JOIN  
    dbo.Districts ON dbo.Projects.DistrictID = dbo.Districts.ID
WHERE 
    dbo.Purpose.PurposeName = N'Residential'

这是此程序的结果:



ID DistrictsName PurposeName 
 1   District1    residential
 2   District1    residential
 3   District2    residential
 4   District2    residential




我希望显示没有重复或具有不同值的DistrictsName,我还在项目记录中每个区域还有一个项目。这就是我想要展示的内容:



ID DistrictsName PurposeName 
 1   District1    residential
 2   District2    residential




我是如何得到这个结果的,  任何帮助表示赞赏。

2 个答案:

答案 0 :(得分:2)

为什么人们在视图更合适时使用存储过程?我从来没有理解这一点。这似乎是SQL Server用户所特有的。

无论如何,你可以通过聚合做你想做的事情:

SELECT ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) as id, 
       d.DistrictName, p.PurposeName
FROM dbo.Projects pr INNER JOIN 
     dbo.Purpose pu
     ON pr.PurposeID = pu.ID INNER JOIN  
     dbo.Districts d
     ON pr.DistrictID = d.ID
WHERE pu.PurposeName = N'Residential'
GROUP BY d.DistrictName, p.PurposeName;

使用表别名可以使查询更容易编写和阅读。

另外,我不理解输出的id列。你为什么要构建一个新的id?在任何情况下,这都是您的数据所暗示的。

答案 1 :(得分:-1)

使用DISTINCT语句删除重复项:

CREATE PROCEDURE [dbo].[SearchResidentialProjects]   
AS
SELECT DISTINCT
    dbo.Projects.ID,
    dbo.Districts.DistrictName,
    dbo.Purpose.PurposeName
FROM 
    dbo.Projects 
INNER JOIN 
    dbo.Purpose ON dbo.Projects.PurposeID = dbo.Purpose.ID 
INNER JOIN  
    dbo.Districts ON dbo.Projects.DistrictID = dbo.Districts.ID
WHERE 
    dbo.Purpose.PurposeName = N'Residential'