ALTER PROCEDURE [dbo].[TEST_01]
(
@StartDate DateTime,
@EndDate DateTime
)
AS
BEGIN
SET NOCOUNT ON;
Declare @sql as nvarchar(MAX);
SET @sql = @sql + ';WITH CTE_ItemDetails
MAX(D.Name) as Name,
SUM(ISNULL(DT.col1, 0)) AS col1,
SUM(ISNULL(DT.col2, 0)) AS col2,
SUM(ISNULL(DT.col3, 0)) AS col3,
GROUPING(D.ItemType) AS ItemTypeGrouping
FROM Items D
INNER JOIN Details DT ON DT.ItemId = D.ItemId
INNER JOIN Report R ON R.ReportId = DT.ReportId
where 1=1'
SET @sql = @sql + ' AND (R.ReportDate >= ' + @StartDate + 'AND R.ReportDate <=' + @EndDate +')'
IF @someOtherVariable is not null
SET @sql = @sql + ' AND R.someColumn IN (''' +replace(@someOtherVariableValues,',','')+''+')'
SET @sql = @sql + 'SELECT col1, col2, col3 FROM CTE_ItemDetails'
EXECUTE (@sql)
END
我有一個類似於上面的T-SQL代碼的存儲過程。 (請注意,我刪除了很多代碼,我覺得這與我所得到的錯誤無關) 當我執行它時,出現以下錯誤。錯誤消息轉換日期時間從字符串轉換失敗
從字符串轉換datetime時轉換失敗。
我的參數值有以下格式
exec TEST_01 @StartDate=N'4/1/2016 12:00:00 AM',@EndDate=N'4/30/2016 12:00:00 AM'
看起來麻煩是方法,我在動態線路設置以下
SET @sql = @sql + ' AND (R.ReportDate >= ' + @StartDate + 'AND R.ReportDate <=' + @EndDate +')'
的SQL語句是什麼最好的日期格式我可以申請避免錯誤。
您需要引用日期,您應該將其更改爲'@sql +'AND(R.ReportDate> ='''+ @StartDate +'''AND R.ReportDate <='''+ @EndDate +' '')' – Siyual
@Siyual這將返回相同的錯誤 – StackTrace