需要相互匹配的 where 子句中的多个“in"语句

2021-09-10 00:00:00 sql tsql sql-server-2008 sql-server

我有一个很长的查询,它本质上是以下内容的扩展:

I have a very long query that is essentially an extension of the following:

update  property.lease_period
set     scca_uplift = '110',
        scca_notes_code = '21006'
where   (suite_id = 'CCBG08' and lease_id = '205059')
        or (suite_id = 'CCBG14' and lease_id = '152424')
        or (suite_id = 'CCCF048' and lease_id = '150659')

完成后,此 where 子句将有大约 40 行.为了使这项任务更容易,我希望做一些类似于以下的事情:

The where clause for this will have ~40 rows when complete. In order to make this task easier I was hoping to do something similar to the following:

update  property.lease_period
set     scca_uplift = '110',
        scca_notes_code = '21006'
where   suite_id in('CCBG08', 'CCBG14', 'CCCF048')
        and lease_id in('205059', '152424', '150659')

不幸的是,lease_id 不是唯一字段,同一个suite_id 可以有多个lease_id(因此随后第二个查询不可用).

Unfortunately lease_id isn't a unique field and there can be multiple lease_id's to the same suite_id (so subsequently the second query is unusable).

鉴于此解决方案不起作用,是否有更好的方法来执行第一个更新语句?

Is there a better way to do the first update statement given that this solution won't work?

推荐答案

您可以创建表类型并通过它传递值,如下所示:

You may create table type and pass the values thru it, like that:

CREATE TYPE Suite_Lease AS TABLE
(
suite_id varchar(15) NOT NULL,
lease_id varchar(15) NOT NULL
)
GO
CREATE PROC DoUpdate
  @Params Suite_Lease READONLY,
  @uplift varchar(15),
  @code varchar(15)
AS
  update  property.lease_period  set
     scca_uplift = @uplift,
     scca_notes_code = @code
  from property.lease_period tab
  JOIN @params filt
    on tab.suite_id=filt.suite_id AND tab.lease_id=filt.lease_id

这将使您的过程缓存保持干燥和清洁,而不是如果您使用多个大" where 子句

This will keep your Procedure cache dry and clean, instead if you using multiple "big" where clauses

如何将表参数传递给存储过程(c#):

        DataTable dt = new DataTable();
        dt.Columns.Add(new DataColumn("suite_id", typeof (string)) {AllowDBNull = false, MaxLength = 15});
        dt.Columns.Add(new DataColumn("lease_id", typeof (string)) {AllowDBNull = false, MaxLength = 15});
        dt.Rows.Add("CCBG08", "205059");

        ... add more rows for match

        using (var c = new SqlConnection("ConnectionString"))
        {
            c.Open();
            using(var sc = c.CreateCommand())
            {
                sc.CommandText = "DoUpdate";
                sc.CommandType = CommandType.StoredProcedure;
                sc.Parameters.AddWithValue("@uplift", "110");
                sc.Parameters.AddWithValue("@code", "21006");
                sc.Parameters.Add(new SqlParameter("@Params", SqlDbType.Structured) { TypeName = null, Value = dt });
                sc.ExecuteNonQuery();
            }
        }

相关文章