How do I pass a list as a parameter in a stored procedure?

前端 未结 7 1511
暖寄归人
暖寄归人 2020-12-02 22:15

Looking to pass a list of User IDs to return a list names. I have a plan to handle the outputed names (with a COALESCE something or other) but trying to find the best way to

7条回答
  •  自闭症患者
    2020-12-02 22:38

    As far as I can tell, there are three main contenders: Table-Valued Parameters, delimited list string, and JSON string.

    Since 2016, you can use the built-in STRING_SPLIT if you want the delimited route: https://docs.microsoft.com/en-us/sql/t-sql/functions/string-split-transact-sql

    That would probably be the easiest/most straightforward/simple approach.

    Also since 2016, JSON can be passed as a nvarchar and used with OPENJSON: https://docs.microsoft.com/en-us/sql/t-sql/functions/openjson-transact-sql

    That's probably best if you have a more structured data set to pass that may be significantly variable in its schema.

    TVPs, it seems, used to be the canonical way to pass more structured parameters, and they are still good if you need that structure, explicitness, and basic value/type checking. They can be a little more cumbersome on the consumer side, though. If you don't have 2016+, this is probably the default/best option.

    I think it's a trade off between any of these concrete considerations as well as your preference for being explicit about the structure of your params, meaning even if you have 2016+, you may prefer to explicitly state the type/schema of the parameter rather than pass a string and parse it somehow.

提交回复
热议问题