值未传递给sql server中的动态查询

时间:2017-05-04 18:19:54

标签: sql debugging dynamic

是否可以在传递参数值后打印Dynamic select语句。当我打印SELECT @ SQL时。它只给出没有参数值的select语句。在我的下面的过程中,动态select语句在传递后没有给出正确的输出参数。但是当我直接将参数值传递给select语句时,它给出了正确的输出。在我的下面的程序中,拆分功能正常工作。请参阅 if语句不能正常工作。

CREATE TYPE TableVariable AS TABLE
(
    id int identity(1,1),
    field_ids        INT,
    value    VARCHAR(MAX)
)


Alter PROCEDURE Testing
(
    @TableVar TableVariable READONLY,
    @Catalog_id INT


)
AS
Declare @maxPK INT
Declare @pk INT 
Declare @fid INT
Declare @is_List SMALLINT
Declare @val VARCHAR(MAX)
Declare @field_Type VARCHAR(50)
Declare @Where VARCHAR(MAX)
Declare @SQL NVARCHAR(MAX);
Set @pk = 1
BEGIN
   BEGIN TRY
    SET NOCOUNT ON;
     Select @maxPK = count(*) From @TableVar 
     SELECT @Catalog_id
     Set @SQL = 'SELECT DISTINCT v1.entity_id from values v1 inner join listings l ON v1.entity_id = l.entity_id WHERE l.c_id=@Catalog_id'

While @pk <= @maxPK
BEGIN


     SELECT @fid= field_ids FROM @TableVar where id=@pk;
     SELECT @val= value     FROM @TableVar where id=@pk;
     SELECT @field_Type=type,@is_List=is_list FROM FIELD WHERE ID=@fid
     IF (@is_List = 0) 
        BEGIN
     SET @SQL += ' and exists (select 1 from values v'+convert(varchar(15),@pk+1)+' where v1.entity_id = v'+convert(varchar(15),@pk+1)+'.entity_id and v'+convert(varchar(15),@pk+1)+'.field_id=@fid and(value IN(SELECT val FROM spliting(@val,'',''))))' 
     SELECT @fid
        END
     else IF (@is_List = 1 OR @field_Type = 'xy')
        BEGIN
        SET @SQL += ' and exists (select 1 from values v'+convert(varchar(15),@pk+1)+' where v1.entity_id = v'+convert(varchar(15),@pk+1)+'.entity_id and v'+convert(varchar(15),@pk+1)+'.field_id=@fid and(value in(@val)))' 
        SELECT @fid
        END
     Select @pk = @pk + 1

END
EXECUTE SP_EXECUTESQL @SQL, N'@Catalog_id int,@fid int,@val varchar(max)',@Catalog_id=@Catalog_id,@fid=@fid,@val=@val  
SELECT @SQL
END TRY

    BEGIN CATCH

    END CATCH

END
DECLARE @DepartmentTVP AS TableVariable;
insert into @DepartmentTVP values(1780,'Smooth As Silk Deep Moisture Shampoo,Smooth As Silk Deeper Moisture Conditioner')
--insert into @DepartmentTVP values(1780,'Smooth As Silk Deeper Moisture Conditioner')
insert into @DepartmentTVP values(1782,'037-05-1129')
insert into @DepartmentTVP values(2320,'["fairtrade","usda_organic","non_gmo_verified"]')
SELECT * FROM @DepartmentTVP
EXEC Testing @DepartmentTVP,583

1 个答案:

答案 0 :(得分:1)

在陈述之前就是:

EXECUTE SP_EXECUTESQL @SQL, N'@Catalog_id int,@fid int,@val varchar(max)',@Catalog_id=@Catalog_id,@fid=@fid,@val=@val  

型:

print @SQL