【问题标题】:how to set the default value of the column when there is null value in stored procedure存储过程中存在空值时如何设置列的默认值
【发布时间】:2017-05-07 23:50:37
【问题描述】:

您好,我正在使用存储过程从不同的表中获取数据,这是我的存储过程。

  SELECT
  ev.Id,
  ev.Title,
  ev.PageUrl,
  ev.FromDate,
  ev.ToDate,
  ev.Isactive,
  CONVERT(char(10), eventtime, 108) as EventTime,
  ev.UserType,
  ev.Street,
  ev.Image,
  ev.Description,
  ev.City,
  ev.CountryCode,
  ev.CategoryId,
  ev.UserId,
  ev.StateCode,
  cm.Name as 'CountryName',
  sm.name as 'StateName',
  asp.FirstName as 'FirstName',
  Cat.Name as 'CategoryName',
  ev.ZipCode
 from events ev
 inner join countrymaster cm on ev.CountryCode=cm.Id
 inner join statemaster sm on ev.StateCode=sm.Id
 inner join category cat on ev.Categoryid=cat.Id
 left join aspnetusers asp on ev.userid=asp.Id
 order by createddate desc  

在第七列

CONVERT(char(10), eventtime, 108) as EventTime,

我通过投射角色来获取事件时间 但是当我的事件时间为空时,它会抛出这样的错误

从“System.String”到“System.TimeSpan”的无效转换。

事件时间的数据类型是时间。

那么,如果 eventtime 列中没有值,我该如何设置它的默认值。

【问题讨论】:

    标签: sql sql-server stored-procedures default-value


    【解决方案1】:

    在该列上使用COALESCE

    CONVERT(char(10), COALESCE(eventtime, GETDATE()), 108) AS EventTime
    

    这将使用当前日期/时间作为默认值,尽管您可以使用此方法使用任何您想要的默认值。

    【讨论】:

      【解决方案2】:

      使用CASE 类似的表达式

      CASE WHEN eventtime IS NULL THEN GETDATE()
      ELSE CONVERT(char(10), eventtime, 108) END AS EventTime,
      

      【讨论】:

        【解决方案3】:
        CONVERT(char(10), isnull(eventtime,getdate()), 108) as EventTime
        

        【讨论】:

          【解决方案4】:

          使用ISNULL() 检查事件时间是否为NULL。如果它为空,那么您可以根据您的选择替换空字符串'' 或其他日期。

          CONVERT(char(10), ISNULL(eventtime,''), 108) as EventTime  // If you want to replace with empty string
          
          CONVERT(char(10), ISNULL(eventtime,GETDATE()), 108) as EventTime  // If you want to replace with current date
          
          DECLARE @default datetime='2016-12-22 16:43:22.560'
          CONVERT(char(10), ISNULL(eventtime,@default), 108) as EventTime  // If you want to relace it with some variable.
          

          【讨论】:

            【解决方案5】:

            请使用

            CONVERT(char(10), isnull(eventtime,getdate()), 108) as EventTime

            【讨论】:

              猜你喜欢
              • 2010-09-14
              • 2014-12-09
              • 1970-01-01
              • 2014-04-27
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2015-11-12
              • 2012-08-06
              相关资源
              最近更新 更多