Search code examples
sql-servert-sqlsql-server-2000

Splitting A String into Multiple Values in SQL Server 2000


I'm asking the question on behalf of someone that works for my client that asked me this. I'm actually more familiar with mySQL than SQL Server, but unfortunately, SQL Server is what the client has used for years.

The question basically this: Is there a way in SQL Server to split a string into multiple values (e.g. array?) that can be used in a WHERE statement.

Here's a PHP example of what I'm talking about.

<?php
    $string = "10,11,12,13";
    $explode = explode(",", $string);
?>

$explode would be equal to array(10,11,12,13). What I need to do is something like this:

SELECT {long field list] FROM {tables} WHERE hour IN SPLIT(",", "10,11,12,13")

With SPLIT being my pseudo-code function that performs the splitting

The reason why I'm not doing this in, let's say, PHP, is because the query is being constructed by reporting software where we can't perform logic (such as my PHP code) before sending it to the database, and the multiple values are being returned by the software as a single string separated by pipes (|).

Unfortunately I do not have access to the reporting software (I think he said it was called Logi or LogiReports or something) or the query my associate was drafting up, but all that is really important for this question is the WHERE clause.

Any ideas?


Solution

  • Dynamic SQL can be used:

    declare @in varchar(10)
    set @in = '10,11,12,13'
    exec ('SELECT {long field list] FROM {tables} WHERE hour IN (' + @in + ')')