在CASE WHEN语句中使用TRY_PARSE的问题

时间:2018-03-19 11:58:26

标签: sql sql-server stored-procedures tryparse

我需要用不同的格式来验证日期 public class asItHappened extends BaseAdapter { private Activity context; private String[] eventType; private final Integer[] imgid; public asItHappened(Context context, String[] event, Integer[] icon) { this.context = context; this.eventType=event; this.imgid=icon; } @Override public int getCount() { return eventType.length; } @Override public Object getItem(int i) { return null; } @Override public long getItemId(int i) { return 0; } @NonNull @Override public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) { LayoutInflater inflater=context.getLayoutInflater(); View rowView=inflater.inflate(R.layout.asithappens_listview, null,true); TextView txtTitle = (TextView) rowView.findViewById(R.id.txtEvent); ImageView imageView = (ImageView) rowView.findViewById(R.id.imgEvent); rowView.findViewById(R.id.textView1); txtTitle.setText(eventType[position]); imageView.setImageResource(imgid[position]); return rowView; } } 我可能会收到Thursday March 15, 2018, 05-21-1995, 04.03.1934之类的无效日期。我使用以下查询来验证存储过程中的日期,这里我将日期插入日期列并设置错误标记如果有无效日期。

N/A, #### etc.,

我的错误为INSERT INTO table_name(date_column,date_error) SELECT CASE WHEN TRY_PARSE(date_column AS datetime USING 'en-US') is NULL THEN date_column ELSE TRY_PARSE(date_column AS datetime USING 'en-US') END as date_column, CASE WHEN TRY_PARSE(date_column AS datetime USING 'en-US') is NULL THEN 1 ELSE 0 END as date_error FROM @temp_table; ,日期值为Conversion failed when converting date and/or time from character string

2 个答案:

答案 0 :(得分:0)

您不能在一列中放置两种不同的类型

这可能适合你

declare @T table (pk int identity primary key, varDt varchar(100));
insert into @T (varDt) values ('Thursday March 15, 2018'), ('05-21-1995'), ('N/A'), ('####'), ('easter'), ('');
declare @Tf table (pk int primary key, varDt varchar(100), needFix bit, dt datetime);
insert into @Tf
select t.pk, t.varDt 
     , case when TRY_PARSE(t.varDt AS datetime USING 'en-US') is null then 1 else 0 end as needFix
     , TRY_PARSE(t.varDt AS datetime USING 'en-US') as dt     
from @T t;
select * 
from @Tf tf 
order by needFix desc, pk;

答案 1 :(得分:0)

感谢您的所有评论。正如@ gordon-linoff所说,我们在CASE WHEN Statement中不能有两种不同的数据类型。所以,我将else语句CAST到varchar。

INSERT INTO table_name(date_column,date_error) 
SELECT 
    CASE WHEN TRY_PARSE(date_column AS datetime USING 'en-US') is NULL THEN date_column
        ELSE CAST(TRY_PARSE(date_column AS datetime USING 'en-US') AS varchar(max))
        END as date_column,
    CASE WHEN TRY_PARSE(date_column AS datetime USING 'en-US') is NULL THEN 1
        ELSE 0
        END as date_error
    FROM @temp_table;