如何正确地将参数传递给EXEC sp_executesql
语句?
这就是我现在所拥有的,但我遇到了错误:
alter PROCEDURE [dbo].[usp_getReceivedCases]
-- Add the parameters for the stored procedure here
@LabID int,
@RequestTypeID varchar(max),
@BeginDate date,
@EndDate date
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
declare @statement nvarchar(4000)
set @statement = N'select SentToLab,
FROM dbo.vEmailSent
WHERE SentToLab_ID=@LabID and convert(date,DateSent) >= @BeginDate
and CONVERT(date, datesent) <= @EndDate
and RequestType_ID in ( @RequestTypeID )
EXEC sp_executesql @statement,N'@LabID int', @LabID, N'@BeginDate date', @BeginDate,N'@EndDate date', @EndDate, @RequestTypeID=@RequestTypeID
END
RequestTypeID是逗号分隔的整数列表,如下所示:“1,2,3,4,5”
这是我的尝试#2,也是不成功的
declare @statement nvarchar(4000)
SET @statement =' select SentToLab_ID
FROM dbo.vEmailSent
WHERE
SentToLab_ID='+@LabID+' and convert(date,DateSent) >= '+@BeginDate +'
and CONVERT(date, datesent) <= '+@EndDate+'
and RequestType_ID in ('+ @RequestTypeID+' )
group by FileStream_ID, SentToLab_ID'
EXEC(@statement)
操作数类型冲突:日期与int
不兼容
答案 0 :(得分:66)
这是一个简单的例子:
EXEC sp_executesql @sql, N'@p1 INT, @p2 INT, @p3 INT', @p1, @p2, @p3;
您的电话将是这样的
EXEC sp_executesql @statement, N'@LabID int, @BeginDate date, @EndDate date, @RequestTypeID varchar', @LabID, @BeginDate, @EndDate, @RequestTypeID
答案 1 :(得分:2)
这也有效....有时您可能想要在实际EXEC调用之外构造参数的定义。
DECLARE @Parmdef nvarchar (500)
DECLARE @SQL nvarchar (max)
DECLARE @xTxt1 nvarchar (100) = 'test1'
DECLARE @xTxt2 nvarchar (500) = 'test2'
SET @parmdef = '@text1 nvarchar (100), @text2 nvarchar (500)'
SET @SQL = 'PRINT @text1 + '' '' + @text2'
EXEC sp_executeSQL @SQL, @Parmdef, @xTxt1, @xTxt2
答案 2 :(得分:0)
如果需要将<!-- SmartMenus jQuery plugin -->
<script src="lib/jquery.smartmenus.min.js" type="text/javascript"></script>
<script src="lib/renderMenu.js"></script>
与sp_executesql
变量一起使用:
OUTPUT
答案 3 :(得分:-1)
也许有帮助:
declare
@statement AS NVARCHAR(MAX)
,@text1 varchar(50)='hello'
,@text2 varchar(50)='world'
set @statement = '
select '''+@text1+''' + '' beautifull '' + ''' + @text2 + '''
'
exec sp_executesql @statement;
与以下相同:
select @text1 + ' beautifull ' + @text2