存储过程中存在空值时如何设置列的默认值

how to set the default value of the column when there is null value in stored procedure

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

  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 列中没有值,我该如何设置默认值。

在该列上使用 COALESCE

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

这将使用当前 date/time 作为默认值,但您可以使用此方法使用任何您想要的默认值。

使用CASE这样的表达式

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

使用ISNULL()检查事件时间是否为NULL或not.If是否为空,然后您可以根据您的选择替换空字符串''或其他日期。

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.

请使用

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