如何将输入参数传递给sp_executesql?

时间:2015-09-11 05:32:25

标签: sql sql-server tsql stored-procedures dynamic-sql

在SQL Server 2014中,我尝试创建一个动态WHERE子句。

我已经将查询构建为字符串,但是当我尝试使用sp_executesql执行它时,我收到以下错误: Líne13您必须声明标量变量“@desde”。

我无法弄清楚如何让sp_executesql识别输入参数。

ALTER PROCEDURE [dbo].[seleccionarFacturas] 
    -- Add the parameters for the stored procedure here
    @desde char(8) = null, 
    @hasta char(8) = null,
    @minimo int = null,
    @ciudad int = null
AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;
    DECLARE @tiendas varchar(max);

    DECLARE @tablaFacturas TABLE
    (
        fecha char(8), 
        CO char(8),
        consecutivo varchar(max),
        nombreCliente varchar(max),
        ventaTotal int
    );

    SET @tiendas='(ID_CO=20 OR ID_CO=22 OR ID_CO=23 OR ID_CO=27 OR ID_CO=35 OR ID_CO=39 OR ID_CO=45 OR ID_CO=48 OR ID_CO=55 OR ID_CO=58)';

    DECLARE @dynamicCode nvarchar(max)=
    N'
    SELECT
        FECHA_DCTO,
        ID_CO,
        DETALLE_DOC,
        NOM_CLI_CONTADO,
        (SUM(TOT_VENTA)) AS ventaTotal
    FROM 
        moda.dbo.CMMOVIMIENTO_VENTAS
    WHERE'
        + @tiendas +
        N' AND FECHA_DCTO >= @desde
        AND FECHA_DCTO <= @hasta
    GROUP BY  
        DETALLE_DOC, ID_CO, FECHA_DCTO, NOM_CLI_CONTADO';

    INSERT INTO @tablaFacturas
    EXEC [dbo].[sp_executesql] @dynamicCode;

    SELECT * FROM @tablaFacturas

0 个答案:

没有答案