Usted está tratando de convertir no sólo un string
a int
, pero variosint
s en uno. ¿Espera que su SELECT
devolverá todos los empleados con una identificación incluida en la matriz?
Me doy cuenta de que quería hacer esto sin una función. Sin embargo, así es como lo hago actualmente y funciona muy bien. Toma lo que quieras de mi respuesta.
Este código utiliza un bucle while
que podría mejorarse a un CTE recursivo si está en SQL 2005/2008. Puede utilizar la salida de la función como una tabla que INNER JOIN
le permitirá filtrar rápidamente.
/*
************************************************************************************************************************
Name: ConvertDelimitedListIntoTable
Description: Converts a list of delimited values into a table for use like a dynamic IN statment
Modification History
Date Author Description
========== ============ ====================================
2009-01-31 B. Williams Initial Creation
************************************************************************************************************************
*/
ALTER FUNCTION [dbo].[ConvertDelimitedListIntoTable] (
@list NVARCHAR(MAX) ,@delimiter CHAR(1))
RETURNS @table TABLE (
item VARCHAR(255) NOT NULL)
AS
BEGIN
DECLARE @pos INT ,@nextpos INT ,@valuelen INT
SELECT @pos = 0 ,@nextpos = 1
WHILE @nextpos > 0
BEGIN
SELECT @nextpos = CHARINDEX(@delimiter,@list,@pos + 1)
SELECT @valuelen = CASE WHEN @nextpos > 0 THEN @nextpos
ELSE LEN(@list) + 1
END - @pos - 1
INSERT @table (item)
VALUES (CONVERT(INT,SUBSTRING(@list,@pos + 1,@valuelen)))
SELECT @pos = @nextpos
END
DELETE FROM @table
WHERE item = ''
RETURN
END
Uso:
DECLARE @intArray varchar(200)
SELECT *
FROM tbl_Employee e
INNER JOIN dbo.ConvertDelimitedListIntoTable(@intArray,',') arr
ON e.EmployeeID = arr.Item
También puede ser una forma rápida de hacer esto con una mesa tally
.
¿Qué versión de SQL Server? ¿Y puedes cambiar el código que está llamando a tu sp? –
@Damien SQL Server 2005. Sí, puedo cambiar el código llamando a mi sp. – Kukoy
ratas. Para 2008, sugiero cambiar a usar parámetros con valores de tabla. –