我编写了下面的SQL并尝试使用变量。
--Select DB
USE [gkretail_master]
--Declare Varibles
DECLARE @StartDate DATE;
DECLARE @EndDate DATE;
DECLARE @SQL VARCHAR(8000);
--Set Variables
SET @StartDate = '2018-05-23 00:00:00.000';
SET @EndDate = '2018-05-23 23:59:00.000'
SET @SQL =
'SELECT
RETAIL_STORE_NUMBER AS ''Store Number'',
DESCRIPTION_1 AS ''Store Name'',
CAST(SUM(BRUTTOGES) AS DECIMAL(18,2)) AS ''Total Taken''
FROM [GKRETAIL_MASTER].[GK_BONKOPF]
JOIN [gkretail_master].[GK_STORE_DATA] ON [GK_BONKOPF].[ID_BSNGP] = [GK_STORE_DATA].[ID_BSNGP]
WHERE
AKTDAT > '+ @StartDate +'
AND
AKTDAT < '+ @EndDate +'
GROUP BY [GK_BONKOPF].[ID_BSNGP], DESCRIPTION_1, RETAIL_STORE_NUMBER';
EXECUTE(@SQL);
然而它返回错误:
数据类型varchar和date在add运算符中不兼容。
我已经完成了一些谷歌搜索并尝试使用CAST和转换来解决它,但它会标记更多错误。
有什么想法吗?
答案 0 :(得分:3)
完全。这是您应该使用sp_executesql
传递参数的一个重要原因:
SET @SQL =
'SELECT
RETAIL_STORE_NUMBER AS ''Store Number'',
DESCRIPTION_1 AS ''Store Name'',
CAST(SUM(BRUTTOGES) AS DECIMAL(18,2)) AS ''Total Taken''
FROM [GKRETAIL_MASTER].[GK_BONKOPF]
JOIN [gkretail_master].[GK_STORE_DATA] ON [GK_BONKOPF].[ID_BSNGP] = [GK_STORE_DATA].[ID_BSNGP]
WHERE
AKTDAT > @StartDate
AND
AKTDAT < @EndDate
GROUP BY [GK_BONKOPF].[ID_BSNGP], DESCRIPTION_1, RETAIL_STORE_NUMBER';
EXEC sp_executesql @SQL,
N'@StartDate date, @EndDate date',
@StartDate = @StartDate, @EndDate = @EndDate;