2

我正在尝试将参数数组发送到存储过程

SELECT [id_Curso] AS IDCurso
  ,[Cod_Estabelecimento] AS CodEstabelecimento
  ,[Des_Estabelecimento] AS DesEstabelecimento
  ,[Cod_Curso] AS CodCurso
  ,[Des_Curso] AS DescCurso
  ,[Cod_Grau] AS CodGrau
  ,[Des_Grau] AS DescGrau
  ,[Cod_Area_Educacao] AS CodAreaEducacao
  FROM [BEP_DEV].[dbo].[Curso]
  where [Cod_Area_Educacao] in @List

DECLARE @List VARCHAR(MAX);
SELECT @List = '(1,2,3,4)';

SELECT [id_Curso] AS IDCurso
  ,[Cod_Estabelecimento] AS CodEstabelecimento
  ,[Des_Estabelecimento] AS DesEstabelecimento
  ,[Cod_Curso] AS CodCurso
  ,[Des_Curso] AS DescCurso
  ,[Cod_Grau] AS CodGrau
  ,[Des_Grau] AS DescGrau
  ,[Cod_Area_Educacao] AS CodAreaEducacao
  FROM [BEP_DEV].[dbo].[Curso]
where [Cod_Area_Educacao] in (1,2,3,4)

如何将第一个案例转换为第二个案例(有效)?

我也尝试使用 xml,但也无法使其工作。

有什么帮助吗?

4

3 回答 3

13

有多种可能性,但鉴于您使用的是 SQL 2008,第一个选择是使用新的表值参数,您可以在其中一次性将整个表发送到查询或存储过程(在您的情况下,一个具有任意数量 ID 的单列的表)。

首先在你的数据库中创建一个表类型:

CREATE TYPE idTable AS TABLE (id INT)

然后只需使用该类型的参数声明您的过程,并像使用任何其他表一样使用它:

CREATE PROCEDURE SelectList (@IDs idTable READONLY) AS
SELECT * FROM sometable
INNER JOIN @IDs AS idTable ON idTable.id=sometable.id

有一篇很棒的文章详细讨论了这个和其他方法来做你需要的事情http://www.sommarskog.se/arrays-in-sql.html

于 2013-10-11T23:36:08.103 回答
1

您可以使用解析字符串并将值插入表(在您的情况下包含一个 int 列)的 udf,然后将您的 Curso 表加入到通过调用 CSV 字符串上的 udf 产生的表上。

于 2013-10-11T22:44:19.263 回答
0

I would pass it as xml. Its easy and very performant. Here is a good post with the details. https://www.simple-talk.com/blogs/2012/01/05/using-xml-to-pass-lists-as-parameters-in-sql-server/

于 2013-10-11T23:18:45.537 回答