Search code examples
asp.netsql-server-2008table-valued-parameters

Filter table based on Table Valued Parameter and Insert TVP value into Select


I have a TVP with two fields.

sentence_id is the filter to select records from the table and this works perfectly. The TVP also includes a keyword. The TVP looks like this:

Create TYPE [dbo].[sentence_id_list2] AS TABLE(
    [sentence_id] [nvarchar](50) NOT NULL,
    [keyword] [nvarchar](50)
)

I want to pass that keyword for the same sentence_id in the result so it looks like this:

Sentence_Identifier,Keyword,Sentence
123, curious, hello donna, i have a curious problem

Where sentence_id passed in from the TVP is 123, keyword is curious.

This is the stored procedure I have, just can't figure out how to include the keyword in the result.

ALTER Procedure [dbo].[chat_Get_Sentences_Table_Value_Parameter] 
@sentence_keys [dbo].[sentence_id_list2] READONLY
AS
SELECT TOP (100) PERCENT dbo.chat_All_Records_Sentence_Details.Sentence_Identifier, 
dbo.chat_All_Records_Sentence_Details.Sentence,

-- how do I write this to insert the keyword from the TVP into the select?
(SELECT keyword FROM @sentence_keys) AS Keyword 

FROM dbo.chat_All_Records_Sentence_Details 
WHERE (dbo.chat_All_Records_Sentence_Details.Sentence_Identifier 
IN (SELECT sentence_id FROM @sentence_keys))

Solution

  • Instead of using IN simpy use an INNER JOIN:

    SELECT  d.Sentence_Identifier,
            d.Sentence,
            sk.keyword
    FROM    chat_All_Records_Sentence_Details AS d
            INNER JOIN @sentence_keys AS sk
                ON sk.sentence_id = d.Sentence_Identifier;
    

    I have removed TOP 100 PERCENT since this would be optimised away anyway, and also used aliases so that your identifiers are not so long.