Quantcast
Channel: Transact-SQL forum
Viewing all articles
Browse latest Browse all 23857

t-sql 2008 r2 datetime conversion issue

$
0
0

In a sql server 2008 r2 database, I have a column called TransactionPaymentDate. The column is defined
 as varchar(50). The value in the column looks like '05012014'. I need to compare the value of this field
 with data fields that use datetime or smalldatetime.

I have tried the following sql statements so I can convert the value to datetime or smalldatetime:

1. CONVERT(smalldatetime,substring(TransactionPaymentDate,5,4) + '-' + substring(TransactionPaymentDate,1,2)+ '-' + substring(TransactionPaymentDate,3,2))
    **this gives an error message: The conversion of a varchar data type to a smalldatetime data type resulted in an out-of-range value.

2. TransactionPaymentDate = cast(substring(TransactionPaymentDate,5,4) + '-' + substring(TransactionPaymentDate,1,2)+ '-' + substring(TransactionPaymentDate,3,2) as smalldatetime
 This does not work in a where statement.

I want to use to be able to do the following type of a compdarsion:
 DECLARE @startdate  smalldatetime = '01012014'
 DECLARE @enddate smalldatetime = '03192014'

Select * from cust_table
  where TransactionPaymentDate between @startdate and @enddate.

I try the following sql, and I have problems:

Select * from cust_table
 where convert(smalldatetime,substring(TransactionPaymentDate,5,4) + '-' + substring(TransactionPaymentDate,1,2)+ '-' + substring(TransactionPaymentDate,3,2))
 between @startdate and @enddate

Thus can you show me sql that will work for this date comparison I want to do?



Viewing all articles
Browse latest Browse all 23857

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>