当我执行此查询时,我收到错误的'关键字'VIEW'附近的语法错误 请帮帮我,这个查询有什么问题?
EXECUTE sp_executesql
N'
CREATE VIEW LastDayOfMonth
AS
SELECT @MAX = MAX(DATEPART(DAY,CurrencyRateDate))AS CurrencyRateDate FROM Sales.CurrencyRate
WHERE
DATEPART(YEAR,CurrencyRateDate)=@YEAR
AND
DATEPART(MONTH,CurrencyRateDate)= @MONTH',
N' @YEAR CHAR(4),@MONTH CHAR(2)',
@YEAR = '2004',
@MONTH = '02';
答案 0 :(得分:1)
使用视图或使用sp_executesql
,没有明显的理由去做你在这里做的事情。
以下内容应该有效:
DECLARE @MAX INT
DECLARE @YEAR INT
DECLARE @MONTH INT
SET @YEAR = 2004
SET @MONTH = 02
SELECT @MAX = MAX(DATEPART(DAY,CurrencyRateDate))AS CurrencyRateDate FROM Sales.CurrencyRate
WHERE
DATEPART(YEAR,CurrencyRateDate)=@YEAR
AND
DATEPART(MONTH,CurrencyRateDate)= @MONTH
并显示结果:
SELECT @MAX
如果这不是你想要做的,也许你可以编辑问题并澄清一下?
答案 1 :(得分:0)
我认为问题在于使用未声明的变量@MAX。当你想要返回这个值时,你不需要变量,只需这样做:
EXECUTE sp_executesql
N'
CREATE VIEW LastDayOfMonth
AS
SELECT
MAX(DATEPART(DAY,CurrencyRateDate))AS CurrencyRateDate AS Maximum
FROM Sales.CurrencyRate
WHERE
DATEPART(YEAR,CurrencyRateDate)=@YEAR
AND
DATEPART(MONTH,CurrencyRateDate)= @MONTH',
N' @YEAR CHAR(4),@MONTH CHAR(2)',
@YEAR = '2004',
@MONTH = '02';
答案 2 :(得分:0)
你可以尝试一下吗?:
EXECUTE DATABASENAME..sp_executesql
N'
CREATE VIEW LastDayOfMonth
AS
SELECT @MAX = MAX(DATEPART(DAY,CurrencyRateDate))AS CurrencyRateDate FROM Sales.CurrencyRate
WHERE
DATEPART(YEAR,CurrencyRateDate)=@YEAR
AND
DATEPART(MONTH,CurrencyRateDate)= @MONTH',
N' @YEAR CHAR(4),@MONTH CHAR(2)',
@YEAR = '2004',
@MONTH = '02';
如果您仍然遇到问题,那么可能是因为您无法使用parameters
工作views
..
答案 3 :(得分:0)
我有类似的问题。看来你不能在视图中使用参数。而是处理SQL以包含参数:
set @sql = N'create view as select * from table where year = ' + cast(@year as varchar(4));
EXECUTE sp_executesql @sql;