пятница, 11 июня 2010 г.

SQL-полезное (Передача списка/коллекции/множества в хранимую процедуру)

Полезная статья, а также комментарии к ней
продолжение с дополнительными способами и тестированием
через xml
использование табличного типа - описание с картинками

победитель - Табличный тип (НО! только для 2008)
В БД объявляется user defined type в виде таблицы с нужным типом данных. Его можно передавать в хранимую процедуру через объект System.Data.DataTable. В хранимой процедуре этот тип будет виден как t-sql таблица, к которой можно делать запросы.

В MSSQL2008
if object_id('FindItems') is not null
drop proc FindItems
go

if exists(select * from sys.types where name = 'Identifiers')
drop type Identifiers
go

create type Identifiers AS TABLE
( id int primary key);
go

set ansi_nulls on
go
set quoted_identifier on
go

create proc FindItems
(
@categories Identifiers readonly
)
as
begin
select i.Name as ItemName, f.Name as FirmName, c.Name as CategoryName
from Item i
inner join Firm f on i.FirmId = f.FirmId
inner join Category c on i.CategoryId = c.CategoryId
inner join @categories cf on c.CategoryId = cf.Id
end
go

Вызов из С#
List categories = new List() { 1, 2, 3 };

DataTable tbCategories = new DataTable("FilterCategory");
tbCategories.Columns.Add("Id", typeof(int));
categories.ForEach(x => tbCategories.Rows.Add(x));

DataTable table = new DataTable();
using (SqlConnection connection = new SqlConnection("Data Source=(local);Initial Catalog=TableParameters;Integrated Security=SSPI;"))
{
connection.Open();
using (SqlCommand command = new SqlCommand("FindItems", connection) { CommandType = CommandType.StoredProcedure })
{
command.Parameters.AddWithValue("@categories", tbCategories);
using (SqlDataAdapter dataAdapter = new SqlDataAdapter(command))
{
dataAdapter.Fill(table);
}
}
}

Вызов из базы
declare @categories Identifiers

insert into @categories ( id ) values ( 1 )
insert into @categories ( id ) values ( 2 )
insert into @categories ( id ) values ( 3 )
insert into @categories ( id ) values ( 4 )

exec FindItems @categories