如何在Microsoft SQL Server 2008中查询包含日期的记录
Got it, let's work through this problem together. You need to pull records where a column has today's date embedded as a DDMMYYYY string (like 29062020 in your example GT3429062020HYHK). Here's how to make this happen in SQL Server 2008:
Step 1: Generate Today's Date in DDMMYYYY Format
SQL Server 2008 doesn’t have the FORMAT() function (that arrived in 2012), so we’ll build the date string manually to ensure leading zeros for single-digit days and months:
DECLARE @TodayDateStr VARCHAR(8) SET @TodayDateStr = RIGHT('0' + CAST(DATEPART(DAY, GETDATE()) AS VARCHAR(2)), 2) + RIGHT('0' + CAST(DATEPART(MONTH, GETDATE()) AS VARCHAR(2)), 2) + CAST(DATEPART(YEAR, GETDATE()) AS VARCHAR(4))
RIGHT('0' + ..., 2)ensures values like6(June) become06and9(9th day) become09—matching your requiredDDMMYYYYpattern perfectly.GETDATE()grabs the current date/time from your SQL Server instance.
Step 2: Find Records with the Embedded Date
Use a LIKE clause to search for the generated date string anywhere in your target column:
SELECT * FROM YourTableName WHERE YourColumnName LIKE '%' + @TodayDateStr + '%'
Just replace YourTableName with your actual table name and YourColumnName with the column holding strings like GT3429062020HYHK.
Example Breakdown
If today is June 29, 2020, @TodayDateStr becomes 29062020. The LIKE '%29062020%' condition will automatically match any record where the column includes that exact 8-digit date string—exactly like your sample value.
Quick Notes
- This query ignores
NULLvalues in the column, sinceLIKEdoesn’t matchNULLvalues. - If you ever need to check for a specific date (not today), just swap
GETDATE()with a fixed date (e.g.,'2020-06-29') in theDATEPARTcalls.
内容的提问来源于stack exchange,提问作者tartar

