使用SQL Server

时间:2016-12-19 10:18:05

标签: 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)

我想选择DistrictsName <{1}}

PurposeName = 'residential'

这是我尝试的代码,但它不起作用,不确定它是真还是假, 这是执行此过程的结果:

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

i want it to be like this :
ID DistrictsName PurposeName 
 1   District1    residential
 2   District2    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'

我是SQL Server的新手,所以感谢任何帮助。

1 个答案:

答案 0 :(得分:0)

根据您的示例数据,您对项目ID不感兴趣 - 在您的示例中,它与任何项目ID无关。所以这是一种方法。

SELECT 
    dbo.Districts.DistrictName,
    'Residential' As PurposeName
FROM 
    dbo.Districts 
WHERE EXISTS (
    SELECT * 
    FROM 
        dbo.Projects 
    INNER JOIN 
        dbo.Purpose ON dbo.Projects.PurposeID = dbo.Purpose.ID 
    WHERE dbo.Projects.DistrictID = dbo.Districts.ID
    AND dbo.Purpose.PurposeName = N'Residential'
    )

但我认为这可能不是你所追求的,它只是帮助我们突出你真正想要的东西

如果你想让id成为一个随意增加的数字,我们可以这样做,但首先请标记SQL Server的版本