Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions sqlglot/dialects/tsql.py
Original file line number Diff line number Diff line change
Expand Up @@ -370,6 +370,16 @@ def _timestrtotime_sql(self: TSQL.Generator, expression: exp.TimeStrToTime):
return sql


def _build_datetrunc(args: t.List) -> exp.TimestampTrunc:
unit = seq_get(args, 0)
this = seq_get(args, 1)

if this and this.is_string:
this = exp.cast(this, exp.DataType.Type.DATETIME2)

return exp.TimestampTrunc(this=this, unit=unit)


class TSQL(Dialect):
SUPPORTS_SEMI_ANTI_JOIN = False
LOG_BASE_FIRST = False
Expand Down Expand Up @@ -570,6 +580,7 @@ class Parser(parser.Parser):
"SUSER_SNAME": exp.CurrentUser.from_arg_list,
"SYSTEM_USER": exp.CurrentUser.from_arg_list,
"TIMEFROMPARTS": _build_timefromparts,
"DATETRUNC": _build_datetrunc,
}

JOIN_HINTS = {"LOOP", "HASH", "MERGE", "REMOTE"}
Expand Down Expand Up @@ -936,6 +947,7 @@ class Generator(generator.Generator):
exp.Trim: trim_sql,
exp.TsOrDsAdd: date_delta_sql("DATEADD", cast=True),
exp.TsOrDsDiff: date_delta_sql("DATEDIFF"),
exp.TimestampTrunc: lambda self, e: self.func("DATETRUNC", e.unit, e.this),
}

TRANSFORMS.pop(exp.ReturnsProperty)
Expand Down
24 changes: 24 additions & 0 deletions tests/dialects/test_tsql.py
Original file line number Diff line number Diff line change
Expand Up @@ -2090,3 +2090,27 @@ def test_next_value_for(self):
"oracle": "SELECT NEXT VALUE FOR db.schema.sequence_name",
},
)

# string literals in the DATETRUNC are casted as DATETIME2
def test_datetrunc(self):
self.validate_all(
"SELECT DATETRUNC(month, 'foo')",
write={
"duckdb": "SELECT DATE_TRUNC('MONTH', CAST('foo' AS TIMESTAMP))",
"tsql": "SELECT DATETRUNC(MONTH, CAST('foo' AS DATETIME2))",
},
)
self.validate_all(
"SELECT DATETRUNC(month, foo)",
write={
"duckdb": "SELECT DATE_TRUNC('MONTH', foo)",
"tsql": "SELECT DATETRUNC(MONTH, foo)",
},
)
self.validate_all(
"SELECT DATETRUNC(year, CAST('foo1' AS date))",
write={
"duckdb": "SELECT DATE_TRUNC('YEAR', CAST('foo1' AS DATE))",
"tsql": "SELECT DATETRUNC(YEAR, CAST('foo1' AS DATE))",
},
)
Loading