How to pass large number of parameters in stored procedure from code to SQL Server

前端 未结 4 1547
情话喂你
情话喂你 2021-01-24 05:13

How to pass a large number of parameters (say 20+) to stored procedure from code?

Like we can group all the parameters in one class object and then pass it across, but h

相关标签:
4条回答
  • 2021-01-24 05:37

    First, look at the design that requires so many parameters - is there a way you can reduce the need to send so much information to the server?

    Secondly, go back to the first point again because it still "smells" wrong :-)

    Then you can do things like:

    • Split the stored procedure. If you don't have to pass all the data in as a single related lump, then you could split one SP into several that do distinct parts of the overall action (e.g. update the users name and address details separately from adding their latest purchase, or whatever)

    • combine parameters. If you have five boolean values that indicate various options, then you could combine them into a single "flags" byte with bitwise operations. Or if you have two 32-bit ints that only hold values between 0..5,000, then they could be combined into a single 32-bit int. etc.

    • Serialise all the parameters into a "file format" and send the data as a single binary or text parameter, which you deserialise in your stored procedure.

    Of course, these approaches mean encoding and decoding a lot of parameters every time which may be worse than passing them all separately. Indeed, one could argue that the SQL call mechanisms are already doing the above for you.

    0 讨论(0)
  • 2021-01-24 05:37

    You shouldn't normally need lots of variables to store parameters; you will need to add SqlParameter (etc) per arg, but you can set them in a loop (/etc).

    0 讨论(0)
  • The Best way to do it in 2.0 is to pass an XML containing all your parameters to the stored procedure and then use OPENXML to obtain each paramters. Use it however you want then in the SP.

    Refer these links

    Passing Parameters as Xml to a Stored Procedure and http://www.eggheadcafe.com/articles/20030627c.asp

    0 讨论(0)
  • 2021-01-24 05:51

    If you are using SQL Server 2008, use a table-valued parameter. If you are not familiar, it basically allows you to pass a table as a param to a stored procedure. The benefit is that you can structure the DataTable you pass in to look however you want.

    I did something like this and instead of passing dozens of params, I passed in a single TVP with two columns [KEY] and [VALUE]. That way when your parameters change in the future, there exists a layer of abstraction to insulate the migration. Of course, how you choose to implement it depends on the situation.

    0 讨论(0)
提交回复
热议问题