Home > Net >  How to use TO_CHAR function functionality in SQL Server
How to use TO_CHAR function functionality in SQL Server

Time:09-18

I have a table named Transaction. I need to use TO_CHAR function sql server. But there is no TO_CHAR function Is there any conversion function in SQL Server for TO_CHAR?

This is the query i want to write in SQL Server.

select * from Transactions where to_char(Transaction_Date_Time, 'yyyy') like '2022';

Here are the table Transactions

Transaction_ID Transaction_Amount Transaction_Date Reciver_ACC_No Account_No
TRA2022072500001 60000 2022-06-15 14:28:60 ACC2022050005 AC20210500001
TRA2022072500005 3000 2022-06-20 13:37:40 ACC2022050006 AC19990300007

CodePudding user response:

If you need to compare the year then use DATEPART function

WHERE DATEPART(YEAR, Transaction_Date_Time) = 2022

Even when the data type is string and do not have date format to cast then use CHARINDEX function:

Where CHARINDEX('2022', Transaction_Date_Time) > 0

CodePudding user response:

The best way to compare dates by year is to use ranges. This would apply to Oracle also. This allows you to hit indexes properly.

For example:

WHERE Transaction_Date_Time >= '20220101' AND Transaction_Date_Time < '20230101'
  • Related