如何在存储过程中将测试数据表作为参数传递

时间:2019-04-19 14:18:54

标签: sql-server testing parameters datatables user-defined-types

我有一个要测试的存储过程。它使用一个已经创建的User-Defined Table Type ([TicketFields]),其本质上只有一个名为fieldNames的列,其中包含nvarchar字段名称(“请求者名称”,“请求者组织”等)。然后,它使用@keyword用户参数创建一个临时表,以在所选字段名称中搜索该关键字。我的问题是,当我执行它进行测试时,不能简单地插入datatable作为参数。

ALTER PROCEDURE [dbo].[bcasp_GetTicketsByKeyword] 
@Keyword nvarchar(150),
@fieldsTable [TicketsFields] READONLY 
AS
BEGIN
CREATE TABLE #Ticket(
    [ID] [bigint] NULL,
    [TicketNumber] [nvarchar](255) NULL,
    [Complexity] [nvarchar](255) NULL,
    [NatureOfInquiry] [nvarchar](255) NULL,
    [SMEResponseDetail] [nvarchar](255) NULL
)

declare @fieldName nvarchar(100)
declare @sql nvarchar(max)
declare @initSql nvarchar(max)
set @initSql = 'insert into #Ticket (ID, TicketNumber, Complexity, 
NatureOfInquiry, SMEResponseDetail) SELECT ID, TicketNumber, Complexity, 
CASE
    WHEN Complexity = 1 THEN NatureOfInquiry_T1 
    WHEN Complexity In (2,3,4) THEN NatureOfInquiry_T234
    END, SMEResponseDetail FROM T_Ticket WHERE '
declare @whereClause nvarchar(100)
set @whereClause = ' Like' + '''%' + @Keyword + '%'''
DECLARE tblCursor CURSOR FOR SELECT FieldName from @fieldsTable
OPEN tblCursor
FETCH NEXT from tblCursor into @fieldName

WHILE @@FETCH_STATUS = 0  
BEGIN 
set @sql = @initsql + @fieldName + @whereClause
print @sql
EXEC(@sql)

FETCH NEXT from tblCursor into @fieldName
END
Close tblCursor
deallocate tblCursor

select distinct * from #Ticket 
END 

enter image description here

该场景假设要在“ NatureOfInquiry”和“ SMEResponseDetail”的keyword列中搜索fieldNames“洪水”。我可以在下面插入什么来模拟它并获得正确的行返回?

USE [BCATicketManagementTest]
GO

DECLARE @return_value int

EXEC    @return_value = [dbo].[bcasp_GetTicketsByKeyword]
        @Keyword = N'flood'
        ???
SELECT  'Return Value' = @return_value

GO

1 个答案:

答案 0 :(得分:1)

怎么样

USE [BCATicketManagementTest]
GO

DECLARE @return_value int

DECLARE @fieldsTableTest [TicketsFields]
INSERT INTO @fieldsTableTest
SELECT 'CUSTOMERID' UNION ALL SELECT 'MANAGERID' UNION ALL SELECT 'SOME OTHER FIELD'


EXEC    @return_value = [dbo].[bcasp_GetTicketsByKeyword]
        @Keyword = N'flood'
        @fieldsTable = @fieldsTableTest
SELECT  'Return Value' = @return_value

GO

我不确定如何使用SSMS完成此任务。

有关更多信息,请参见Use Table-Valued Parameters (Database Engine)