0

I'm trying to build an Excel tool that allows users to input a series of article IDs and query our SQL server for said IDs. Problem is that all of these IDs are strings, so I have to input them as '123', '456', '789' - which is obviously not working if I were to execute the SP via

exec SP_test @articleID = '123', '456', '789'

The SP itself is pretty basic:

ALTER PROCEDURE [dbo].[SP_test]
    @articleID as VARCHAR
AS
BEGIN

    SET NOCOUNT ON;

    SELECT
        ARTNR
        , ARTBEZ
    FROM table
    WHERE
        ARTNR IN 
            (@articleID)
END
GO

Like I said, this isn't working because it's not parsing '123' as '123' but rather 123.

I've then found a custom function to split strings in this thread: How to pass string parameter with `IN` operator in stored procedure SQL Server 2008

If I then just execute the query itself (not as a SP), it's actually giving me the proper results:

SELECT
    ARTNR
    , ARTBEZ
FROM table
WHERE
    ARTNR IN 
        (select value from fn_split('123, 456, 789', ','))

But if I then try to turn that into my SP a la

ALTER PROCEDURE [dbo].[SP_test]
    @articleID as VARCHAR
AS
BEGIN

    SET NOCOUNT ON;

    SELECT
        ARTNR
        , ARTBEZ
    FROM table
    WHERE
        ARTNR IN 
            (select value from fn_split(@articleID, ','))
END
GO

it seems to again be parsing the articleIDs incorrectly.

Can anyone clue me in on how to get this to work properly? I've seen the string_split function being thrown around in this context, but m server's compatibility level isn't high enough for that.

  • 1
    Why not use a table type parameter? – Thom A Dec 04 '21 at 18:30
  • 3
    [Bad Habits to Kick : Declaring VARCHAR without (length)](https://sqlblog.org/2009/10/09/bad-habits-to-kick-declaring-varchar-without-length) – Thom A Dec 04 '21 at 18:31
  • 2
    *"it's not parsing '123' as '123' but rather 123."* It's not parsing it as `123` it's passing it as `'1'`. You can't fit more than one character in a `varchar(1)`. – Thom A Dec 04 '21 at 18:32
  • Blimey, was kind of suspecting I was sleeping on something pretty simple - with varchar(MAX) it's actually working perfectly fine. Thank you, kind stranger. – Peter Parker Dec 04 '21 at 18:35
  • If you are on SQL Server 2016+ you can use `STRING_SPLIT` – Charlieface Dec 04 '21 at 18:48
  • Not I **strongly** recommend the accepted answer in that link question, @PeterParker, it's a terrible solution. – Thom A Dec 04 '21 at 18:59
  • Rather than that, honestly, use a set based inline table value function, , `STRING_SPLIT`, or switch to a table type parameter. – Thom A Dec 04 '21 at 19:08

0 Answers0