使用SQL Server 2008检查表中是否存在ID

时间:2013-03-18 22:00:21

标签: sql select sql-server-2008-r2

我在SQL Server 2008中使用select语句时遇到一些麻烦。我正在建立一个售票应用程序网站,我需要确保无法搜索已售出的票证。这是我的SQL存储过程:

    spGetSeatBySection
    @SectionID int
    AS
    SELECT
    [SeatID],
    [SectionID],
    [SeatName],
    [SeatPrice],
    [SeatDesc],
    [SeatIsActive],
  FROM [myDataBase].[dbo].[Seats]
  WHERE SectionID = @SectionID 
  AND SeatIsActive = 1 
  AND **IF EXISTS CLAUSE**;

我尝试了其他一些已经发布的方法,比如if exists('table_name,'column_name')。是否有其他方法可以在不重新设计我的SELECT声明的情况下进行检查?

1 个答案:

答案 0 :(得分:0)

EXISTS

之类的
    SELECT
    [SeatID],
    [SectionID],
    [SeatName],
    [SeatPrice],
    [SeatDesc],
    [SeatIsActive],
  FROM [myDataBase].[dbo].[Seats]
  WHERE SectionID = @SectionID 
  AND SeatIsActive = 1 
  AND EXISTS (SELECT o.SeatID 
              FROM OrderItems o
              WHERE o.SeatID = [Seats].SeatID )

你可能会这样做:

     SELECT
    s.[SeatID],
    s.[SectionID],
    s.[SeatName],
    s.[SeatPrice],
    s.[SeatDesc],
    s.[SeatIsActive],
  FROM [myDataBase].[dbo].[Seats] s
       INNER JOIN OrderItems o ON o.SeatID = s.SeatID 
  WHERE s.SectionID = @SectionID 
  AND s.SeatIsActive = 1