0

我有一张这样的桌子:

Locid       Paydate                 DelDate                 vtid

5           2013-05-07 18:36:50.000 2013-05-07 18:58:32.000   7
5           2013-05-07 18:36:50.000 2013-05-07 18:58:32.000   8
6           2013-05-07 18:36:50.000 2013-05-07 18:58:32.000   7
6         2013-05-07 18:36:50.000 2013-05-07 18:58:32.000     8
7           2013-05-07 18:36:50.000 2013-05-07 18:58:32.000   7

我有一个这样的存储过程:

ALTER PROCEDURE [dbo].[performance] @locid INTEGER=NULL
AS
  BEGIN
      SET NOCOUNT ON;

      SELECT l.LocName,
             v.Vtype,
             SUM(DATEDIFF(MI, t.Paydate, t.DelDate))                                                   AS TotalDiff,
             CONVERT(DECIMAL(10, 1), AVG(CONVERT(NUMERIC(18, 2), DATEDIFF(MI, t.Paydate, t.DelDate)))) AS Average
      FROM   Transaction_tbl t
             LEFT JOIN VType_tbl v
               ON t.vtid = v.vtid
             LEFT JOIN Location_tbl l
               ON t.Locid = l.Locid
      WHERE  t.Locid = @locid
      GROUP  BY v.Vtype,
                l.LocName
  END 

,在这一次我只能通过一个 locid,有时我需要在一个数据集中放 2 个 locid。所以我怎么能自动通过两个locid。

4

2 回答 2

4

您可以更改存储过程以接受表值参数(然后可以接受任意数量的locids)

CREATE TYPE [dbo].[LocationIds] AS TABLE(
    locid INTEGER PRIMARY KEY)

然后

ALTER PROCEDURE [dbo].[performance] 
@LocationIds [dbo].[LocationIds] READONLY
AS

并将其更改WHERE

 WHERE  t.Locid in (SELECT locid FROM  @LocationIds  )

除非名称保证唯一,否则也添加l.Locid到列表中。GROUP BY

于 2013-07-21T10:40:35.217 回答
1

To handle an indertiminate number of id's then you could have them passed as a comma separated string (varchar), split it into a table and then join to it.

Something like this.

ALTER PROCEDURE [dbo].[performance]
    (@ids VARCHAR(MAX))
AS
BEGIN
    SET NOCOUNT ON;

    DECLARE @xml xml = N'<root><r>' + REPLACE(@ids,',','</r><r>') + '</r></root>'

    SELECT 
        l.LocName,
        v.Vtype,
        SUM(DATEDIFF(MI, t.Paydate, t.DelDate)) AS TotalDiff,
        CONVERT(DECIMAL(10, 1), 
            AVG(CONVERT(NUMERIC(18, 2), 
            DATEDIFF(MI, t.Paydate, t.DelDate)))) AS Average
    FROM Transaction_tbl t
    JOIN (
        SELECT t.value('.','INT') id
        FROM @xml.nodes('//root/r') a(t)
    ) x ON x.id = t.id
    LEFT JOIN VType_tbl v
           ON t.vtid = v.vtid
    LEFT JOIN Location_tbl l
           ON t.Locid = l.Locid
    GROUP BY v.Vtype, l.LocName
END
GO

demo

于 2013-07-21T10:49:24.760 回答