SQL Functional Models
SQL Functional Models
In general, statements are executed sequentially- The first statement in a function is executed first,
followed by the second, and so on. There may be a situation when you need to execute a block of code
several number of times. Programming languages provide various control structures that allow more
complicated execution paths. A loop statement allows us to execute a statement or group of statements
multiple times. The following diagram illustrates a loop statement.
In SQL Server, you can use various expressions using CONVERT function to get the same result.
Oracle:
SQL Server:
Conversion summary:
Oracle:
In SQL Server, you can firstly convert a datetime to DATE that does not contain the time part, and
then convert it back to DATETIME or DATETIME2. The time part will be set to zero now:
SQL Server:
-- Get the current datetime with time set to zero
SELECT CONVERT(DATETIME, CONVERT(DATE, GETDATE()));
# 2013-02-11 00:00:00.000
Note that DATE data type is available since SQL Server 2008
You can also convert a datetime to VARCHAR(10) to take the first 10 characters, use style 120 to get
the 'YYYY-MM-DD' format, and then convert back to DATETIME or DATETIME2. The time part will be
zero as well:
SQL Server:
Truncate to Month
If you specify 'MM' or 'MONTH' unit in Oracle TRUNC, the datetime is truncated to month (day is set to
1, and time is set to 00:00:00):
Oracle:
-- Get the current year and month, day is set to 1 and time is set to zero
SELECT TRUNC(SYSDATE, 'MM') FROM dual;
# 2013-02-01 00:00:00
In SQL Server, you can convert a datetime to VARCHAR(7) using style 120 to get the YYYY-MM
format, then add '-01', and convert to DATETIME or DATETIME2:
SQL Server:
-- Get the current year and month, day is set to 1 and time is set to zero
SELECT CONVERT(DATETIME, CONVERT(VARCHAR(7), GETDATE(), 120) + '-01');
# 2013-02-01 00:00:00.000
Truncate to Year
If you specify 'YY' or 'YEAR' unit in Oracle TRUNC, the datetime is truncated to year (month and day
are set to 1, and time is set to 00:00:00):
Oracle:
SQL Server:
You can also use YEAR or DATEPART function to get the year, convert it to string, add '-01-01' and
then convert to DATETIME or DATETIME2:
SQL Server:
Truncate to Hour
If you specify 'HH24' or 'HH' unit in Oracle TRUNC, the datetime is truncated to hour (minutes and
seconds are set to 00:00):
Oracle:
In SQL Server, you can convert a datetime to VARCHAR(13) using style 120 to get the 'YYYY-MM-DD
HH24' format, add ':00:00', and convert to DATETIME or DATETIME2:
SQL Server:
Truncate to Minute
If you specify 'MI' unit in Oracle TRUNC, the datetime is truncated to minute (seconds are set to zero):
Oracle:
-- Get the current datetime with the minute accuracy
SELECT TRUNC(SYSDATE, 'MI') FROM dual;
# 2013-02-11 13:49:00
In SQL Server, you can convert a datetime to VARCHAR(16) using style 120 to get the 'YYYY-MM-DD
HH24:MI' format, add ':00', and convert to DATETIME or DATETIME2:
SQL Server: