将ID数组传递给存储过程

时间:2009-07-15 21:15:12

标签: sql-server database tsql stored-procedures

我有存储过程,我想发送一个值数组。当我发送多个我收到错误时

将数据类型varchar转换为数字时出错。

这是代码。

set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[sp_getTransfer] @TRANSFER_ID int = null, @COMPANY VARCHAR(5),@FORMTYPE VARCHAR(30), @TRANSFER_IDS VARCHAR(500) = NULL, @SEAL_DATE datetime = NULL AS
-- Declare variables
DECLARE @rc Int

IF @SEAL_DATE IS NULL
BEGIN 
SELECT 
COMPANY,
FORMTYPE,
COMPANY_NAME,
COMPANY_ADDRESS1,
COMPANY_ADDRESS2,
IMID,[DESCRIPTION],AMOUNT,AMOUNT_TRANSFER, 
CONSIDERATION,
TRANSFER_ID, 
[DATE],
CURR, 
CMF_NAME_1, 
CMF_NAME_2, 
CMF_ADDR_1, 
CMF_ADDR_2,
CMF_ADDR_3, 
CMF_ADDR_4, 
CMF_POSTAL_CODE,
Cons_Curr =  CASE
WHEN LTRIM(RTRIM(Cons_Curr)) <> '' THEN Cons_Curr
ELSE CURR
END,
-- Cons_Curr,
TRANSFERYEAR,
TRANSFERMONTH,
TRANSFERDAY,
dbo.CurrencyToWords(CURR) AS CURR_WORDS,
---dbo.CurrencyToWords(Cons_Curr) AS CONNS_CURR_WORDS

CONS_CURR_WORDS = CASE 
WHEN LTRIM(RTRIM(CONS_CURR)) <> '' THEN dbo.CurrencyToWords(CONS_CURR)
ELSE dbo.CurrencyToWords(CURR)
END



   FROM 
VW_TRANSFERS
   WHERE 
TRANSFER_ID= @TRANSFER_ID
AND 
FORMTYPE= @FORMTYPE
AND 
COMPANY = @COMPANY
OR 
TRANSFER_ID IN (@TRANSFER_IDS)
END

ELSE
SELECT 
COMPANY,
FORMTYPE,
COMPANY_NAME,
COMPANY_ADDRESS1,
COMPANY_ADDRESS2,
IMID,[DESCRIPTION],AMOUNT,AMOUNT_TRANSFER, 
CONSIDERATION,
TRANSFER_ID, 
[DATE],
CURR, 
CMF_NAME_1, 
CMF_NAME_2, 
CMF_ADDR_1, 
CMF_ADDR_2,
CMF_ADDR_3, 
CMF_ADDR_4, 
CMF_POSTAL_CODE,
--Cons_Curr,
Cons_Curr =  CASE
WHEN LTRIM(RTRIM(Cons_Curr)) <> '' THEN Cons_Curr
ELSE CURR
END,
TRANSFERYEAR,
TRANSFERMONTH,
TRANSFERDAY,
dbo.CurrencyToWords(CURR) AS CURR_WORDS,
---dbo.CurrencyToWords(Cons_Curr) AS CONNS_CURR_WORDS

CONS_CURR_WORDS = CASE 
WHEN LTRIM(RTRIM(CONS_CURR)) <> '' THEN dbo.CurrencyToWords(CONS_CURR)
ELSE dbo.CurrencyToWords(CURR)
END
   FROM 
VW_TRANSFERS
   WHERE 
FORMTYPE= @FORMTYPE
AND 
COMPANY = @COMPANY
AND
DATE = @SEAL_DATE 
OR 
TRANSFER_ID IN (@TRANSFER_IDS)








EXEC sp_getTransfer NULL, fgb, transfer, '124,444,4555,8865,24,55,69', NULL

2 个答案:

答案 0 :(得分:4)

以下代码无效:

TRANSFER_ID IN (@TRANSFER_IDS)

这里描述了几种可行的替代方案:

Arrays and Lists in SQL Server

答案 1 :(得分:0)

您必须将其设置为动态存储过程或循环访问代码中的ID并每次调用存储过程。你知道如何设置动态程序吗?

示例

ALTER Procedure [dbo].[sp_NAME]
 (@id as varchar(max)
)
as
Declare @query1 as nvarchar(max) 
If @Param is null
set @Param = ''

Set @query1 = '
select whatever
from table
where id in('+@id+')'
EXECUTE sp_executesql @query1