我有一个存储过程,我无法弄清楚字符串是如何构建的。
当我在那里没有变量时,SQL语句工作正常,所以它绝对是我写它的方式。我只是一个初学者,对语法不太了解。
以下是代码:
CREATE PROCEDURE [dbo].[SP_SLINVOICE]
@varCURRENCY AS VARCHAR(3)
AS
BEGIN
SET NOCOUNT ON;
DECLARE @SQL NVARCHAR(MAX);
SELECT @SQL = N'SELECT dbo.invmaster.InvNumber
FROM dbo.invmaster INNER JOIN dbo.invdetail ON dbo.invmaster.INVMasterID = dbo.invdetail.INVMasterID
INNER JOIN dbo.Company ON dbo.invmaster.InvCompanyID = dbo.Company.CompanyID
WHERE dbo.InvMaster.InvCurrency = '' + @varCURRENCY + ''
AND dbo.invmaster.DocType <> ''MC''
ORDER BY dbo.invmaster.InvNumber ASC;';
EXEC sp_executesql @sql;
执行时@varCURRENCY不会给我一个错误。但是当我通过参数传递它时,它不起作用。
如果您能看到问题所在,请告诉我。
提前致谢
答案 0 :(得分:2)
你的SQL最终是这样的:
WHERE dbo.InvMaster.InvCurrency = '@varCURRENCY'
所以你没有找到参数的值,你正在寻找@Currency
,我不确定你为什么使用动态SQL,以下应该可以正常工作:
CREATE PROCEDURE [dbo].[SP_SLINVOICE] @varCURRENCY AS VARCHAR(3)
AS
BEGIN
SET NOCOUNT ON;
SELECT dbo.invmaster.InvNumber
FROM dbo.invmaster
INNER JOIN dbo.invdetail
ON dbo.invmaster.INVMasterID = dbo.invdetail.INVMasterID
INNER JOIN dbo.Company
ON dbo.invmaster.InvCompanyID = dbo.Company.CompanyID
WHERE dbo.InvMaster.InvCurrency = @varCURRENCY
AND dbo.invmaster.DocType <> 'MC'
ORDER BY dbo.invmaster.InvNumber ASC;
END
如果由于其他原因需要动态SQL,可以使用以下内容将@varCURRENCY
作为参数传递给sp_executesql
:
DECLARE @SQL NVARCHAR(MAX);
SELECT @SQL = N'SELECT dbo.invmaster.InvNumber
FROM dbo.invmaster INNER JOIN dbo.invdetail ON dbo.invmaster.INVMasterID = dbo.invdetail.INVMasterID
INNER JOIN dbo.Company ON dbo.invmaster.InvCompanyID = dbo.Company.CompanyID
WHERE dbo.InvMaster.InvCurrency = @varCURRENCY
AND dbo.invmaster.DocType <> ''MC''
ORDER BY dbo.invmaster.InvNumber ASC;';
EXEC sp_executesql @sql, N'@varCURRENCY VARCHAR(3)', @varCURRENCY;
答案 1 :(得分:1)
如果要将变量传递给sp_executesql
上下文,则需要将其作为参数传递。
EXECUTE sp_executesql
@sql,
N'@varCurrency varchar(3)',
@varcurrency= @varCurrency;
http://msdn.microsoft.com/en-gb/library/ms188001.aspx
虽然为什么你不只是使用
select ... where dbo.InvMaster.InvCurrency = @varCURRENCY
而不是executeql超出了我。
答案 2 :(得分:0)
您需要将@varCURRENCY
作为参数传递,从Sp中删除额外的'
。
WHERE dbo.InvMaster.InvCurrency = ' + @varCURRENCY + '
或者不要使用动态查询
CREATE PROCEDURE [dbo].[SP_SLINVOICE]
@varCURRENCY AS VARCHAR(3)
AS
BEGIN
SET NOCOUNT ON;
SELECT dbo.invmaster.InvNumber
FROM dbo.invmaster INNER JOIN dbo.invdetail ON dbo.invmaster.INVMasterID = dbo.invdetail.INVMasterID
INNER JOIN dbo.Company ON dbo.invmaster.InvCompanyID = dbo.Company.CompanyID
WHERE dbo.InvMaster.InvCurrency = @varCURRENCY
AND dbo.invmaster.DocType <> 'MC'
ORDER BY dbo.invmaster.InvNumber ASC;