Sql 执行存储过程时返回的语法不正确
我对商店的程序还不熟悉 谁能告诉我这有什么问题吗Sql 执行存储过程时返回的语法不正确,sql,stored-procedures,Sql,Stored Procedures,我对商店的程序还不熟悉 谁能告诉我这有什么问题吗 Create PROCEDURE [dbo].[spCreateProductionReport] @whereClause nvarchar(max) As Begin declare @id int, @itemNum nvarchar(20), @datetimestamp datetime, @tStations_id int declare @counter int, @itemNumPrev nvarchar(20
Create PROCEDURE [dbo].[spCreateProductionReport]
@whereClause nvarchar(max)
As
Begin
declare @id int, @itemNum nvarchar(20), @datetimestamp datetime, @tStations_id int
declare @counter int, @itemNumPrev nvarchar(20)
set @counter = 0
set @itemNumPrev =''
set @whereClause = ''
SET NOCOUNT ON;
create table #Temp
(
id int,
itemNum nvarchar(20),
tStations_id int,
datetimestamp datetime,
groupID int
)
DECLARE db_cursor CURSOR FOR
select id,itemNo,tstations_id,datetimestamp
from
tProduction_Count @whereClause
--where datetimestamp between '2017-03-16 00:00:00' and '2017-03-16 23:59:59'
ORDER BY id ASC
OPEN db_cursor
FETCH NEXT FROM db_cursor INTO @id, @itemNum,@tStations_id, @datetimestamp
我得到的错误是:
'Msg 102,第15级,状态1,程序spCreateProductionReport,第42行
“@whereClause.”附近的语法不正确。必须先声明变量
DECLARE@whereClause nvarchar(max)
而且,这看起来不正确:从tProduction\u Count@whereClause中选择id、itemNo、tstations\u id、datetimestamp
whereClause
变量在这里做什么?您必须首先声明该变量
DECLARE@whereClause nvarchar(max)
而且,这看起来不正确:从tProduction\u Count@whereClause中选择id、itemNo、tstations\u id、datetimestamp
whereClause
变量在这里做什么?您不能在编写的查询中混用参数
您需要使用动态SQL来实现这一点,这样您就可以将整个查询构建为一个字符串
比如:
但是,不能在该动态查询上声明游标,因此一种方法是将该执行的结果插入到临时表中,然后在该表上构建游标
如果您可以通过接收在常规查询中使用的参数来完全避免动态SQL,那就更好了,因为动态SQL可能更难调试,而且如果您从前端接收到动态SQL,您可能会受到SQL注入攻击。您不能在编写的查询中混用参数
您需要使用动态SQL来实现这一点,这样您就可以将整个查询构建为一个字符串
比如:
但是,不能在该动态查询上声明游标,因此一种方法是将该执行的结果插入到临时表中,然后在该表上构建游标
如果您可以通过接收在常规查询中使用的参数来避免动态SQL,这会更好,因为动态SQL可能更难调试,而且如果您从前端接收到动态SQL,您可能会受到SQL注入攻击。Where子句变量是参数还是忘记声明它了?它应该是参数,我将使用WHERE子句从前端获取字符串/文本,并将其用作筛选器这里是@WHERE子句变量a参数,还是您忘记声明它了?它应该是一个参数,我将使用where子句从前端获取字符串/文本,并将其用作此处的筛选器。我已在as begin之前声明@where子句。我们无法分辨第42行的位置。请参见编辑,我添加了另一点,我想使用where子句作为过滤器,我将从前端获取并传递它。有没有更好的方法?第42行实际上是“从生产中选择id、itemNo、tstations\u id、datetimestamp\u Count@whereClause”的一行。我已经在开始之前声明了@whereClause。我们无法知道第42行在哪里。请参见编辑,我添加了另一点,我想使用where子句作为过滤器,我将从前端获取并传递它。有没有更好的方法?第42行实际上是“从tProduction\u Count@where子句中选择id、itemNo、tstations\u id、datetimestamp”的行
EXEC('select id,itemNo,tstations_id, datetimestamp from tProduction_Count ' + @whereClause)