Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
567 views
in Technique[技术] by (71.8m points)

.net - Classic ADO.NET - How to Pass UDT To Stored Procedure?

I have this SQL Server 2008 UDT:

CREATE TYPE [dbo].[IdentityType] AS TABLE(
    [Id] [int] NOT NULL
)

Pretty simple. Basically allows me to hold onto a list of id's.

I have this stored procedure:

CREATE PROCEDURE [dbo].[Scoring_ScoreMultipleLocations]
    @LocationIds [IdentityType] READONLY,
    @DoRanking BIT = 0
AS
BEGIN
   -- irrelevant code.
END

Entity Framework 4.0 does not support executing stored procedures that take user defined table types as a parameter, so i'm reverting to classic ADO.NET. The only other option is passing a comma-seperated string.

Anyway, i found this article, but it's a little hard to follow.

I don't understand what this line of code is doing:

DataTable dt = preparedatatable();

They don't even provide that method, so i have no idea what i'm supposed to do here.

This is my method signature:

internal static void ScoreLocations(List<int> locationIds, bool doRanking)
{
   // how do i create DataTable??
}

So i have a list of int and need to pump that into the UDT.

Can anyone help me out/point me to a clear article on how to achieve this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This article might be a bit more help.

Essentially, you'll create a new DataTable that matches the schema, then pass it as a parameter.

The code of preparedatatable() probably would look something like:

var dt = new DataTable();
dt.Columns.Add("Id", typeof(int));
return dt;

After which, you'd have to add your locationIds:

foreach(var id in locationIds)
{
    var row = dt.NewRow();
    row["Id"] = id;
    dt.Rows.Add(row);
}

Then assign dt as a parameter:

var param = cmd.Parameters.AddWithValue("@LocationIDs", dt);
param.SqlDbType = SqlDbType.Structured;
param.TypeName = "dbo.IdentityType";

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...