【问题标题】:Only begin stored procdure if previous value is less than new value being inserted into table SQL Server仅当先前值小于插入表 SQL Server 的新值时才开始存储过程
【发布时间】:2019-09-20 14:23:28
【问题描述】:

我有一个存储过程。如果日期值高于以前的记录,我只希望它插入新值。

Department   Change    Date
------------------------------------
Catering        3      2018-01-01 08:09:00.000   - Current Record 

Department   Change    Date
-----------------------------------------------
Catering       3       2018-01-02 09:10:00.000   - New record to be inserted 

到目前为止我有这个,但显然选择是错误的。我想在Insert 声明之前做这样的事情

 if select top 1 * 
    from  database.[dbo].[DepartmentChange]
    where Department = @Department
      and Date > @Date
    order by Date desc  
begin 

请帮忙

【问题讨论】:

  • 样本数据和期望的结果会很有帮助。你说你想做一个插入,但你的代码没有insert 语句。
  • 对于初学者,您缺少 if 语句的另一半。 if (select TOP 1...) < @YourInputVariable... 可能是您正在尝试的,但很难用这么少的代码来判断。
  • 完全不清楚你在问什么,或者想做什么。

标签: sql sql-server


【解决方案1】:

这里的细节相当模糊,但我认为您正在寻找类似的东西。

if not EXISTS
(
    select * 
    from database.[dbo].[DepartmentChange]
    where Department = @Department
        and Date > @Date
)
    begin
        --do your insert
    end

else
    begin
        --do something else here
    end

【讨论】:

    【解决方案2】:

    模糊的问题。我假设@Date、@Department 来自新记录。所以也许是这样。 . .

    if @Date > (select isnull(max(date),'1500-01-01') from database.[dbo].[DepartmentChange]
                 where Department = @Department)
       begin
          insert statement here
       end
    

    【讨论】:

    • @Joeysonic - 如果您只想在满足条件时插入(而不是 ELSE),我建议将此作为 where 谓词添加到您的插入语句中,而不是让它变得如此复杂。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多