NOTE: Edited to fix issue with copying and pasting the stored procedure code. My inline tabs were being converted to spaces, so I replaced them with CHAR(9). Also, see note at bottom for a potential real-world example.
This one took me a little while, but I just knew I could figure it out if I kept trying. I wrote it as a stored procedure for easy reuse.
CREATE PROCEDURE InsertListIntoTable
@List varchar(max),
@Delimiter varchar(5),
@TableName varchar(50),
@ColumnName varchar(50),
@ListFilter varchar(max) = ''
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
DECLARE @SqlStmt nvarchar(max)
DECLARE @CrLf char(2); SET @CrLf = CHAR(13) + CHAR(10);
DECLARE @Tab char(1); SET @Tab = CHAR(9);
SET @SqlStmt =
N'INSERT INTO ' + @TableName + @CrLf +
@Tab + N'(' + @ColumnName + ')' + @CrLf +
@Tab + N'SELECT * FROM' + @CrLf +
@Tab + N'(' + @CrLf +
@Tab + @Tab + N'SELECT ' +
REPLACE(@List, @Delimiter, @CrLf + @Tab + @Tab + 'UNION SELECT ') + @CrLf +
@Tab + N') t' + @CrLf
IF LEN(@ListFilter) > 0
SET @SqlStmt = @SqlStmt +
@Tab + N'WHERE ' + @ListFilter + @CrLf
SET @SqlStmt = STUFF(@SqlStmt, CHARINDEX(CAST(@CrLf + @Tab + @Tab + 'UNION' AS nvarchar(50)), @SqlStmt, 1), 0, ' ' + @ColumnName);
PRINT @SqlStmt
--EXEC sp_executesql @SqlStmt
END
Sample usage:
DECLARE @BigArray varchar(max)
SET @BigArray = '1,2,3,5,7,11,13,17,19,23,29,31'
EXEC InsertListIntoTable @BigArray, ',', 'MyTable', 'Column1', 'Column1 IN (1,3,13,31)'
Table Contents:
Column1
1
3
13
31
This is just a simple example. A real-world example might be something like this:
@BigArray = a list of part numbers to add to inventory
EXEC InsertListIntoTable @BigArray, ',', 'Inventory', 'PartNumber',
'EXISTS (SELECT PartNumber FROM RegisteredParts rp WHERE rp.PartNumber=t.PartNumber)'