简体   繁体   English

如何使用动态创建的IN集创建存储过程

[英]How to create a stored procedure with dynamically created IN set

I have some SQL that I am converting to stored procedures via blind requirement/request. 我有一些SQL,我通过盲需求/请求转换为存储过程。 There is a bit of SQL in the application I'm looking at that builds the where clause with a dynamic IN (set) statement. 我正在查看的应用程序中有一些SQL,它使用动态IN(set)语句构建where子句。 I have searched for dynamic stored procedure but nothing close to what I'm looking for has come up for me. 我已经搜索了动态存储过程但是没有接近我正在寻找的东西。 Here is a sample of the WHERE clause: 以下是WHERE子句的示例:

WHERE Var.A = @Param AND Var.Id IN

From here the SQL is built manually using a string builder and then executed. 从这里开始,SQL是使用字符串构建器手动构建的,然后执行。 Not sure how I'd convert this into a stored procedure as I'm fairly new to them. 我不确定如何将其转换为存储过程,因为我对它们还不熟悉。

We are using C# and SQL Server 我们正在使用C#和SQL Server

You could use an user-defined data type. 您可以使用用户定义的数据类型。

On the C# side it would look like this: 在C#端,它看起来像这样:

//Setup a DataTable with the same structure as the SQL Type
var data = new DataTable();
data.Columns.Add("value", typeof(string));

//Populate the table
data.Rows.Add("oneID");
data.Rows.Add("anotherID");

//You create your sql command
cmd.Parameters.Add("@listArgument", data);
//Command execution

On the SQL side you could have a type like this 在SQL方面,你可以有这样的类型

CREATE TYPE [dbo].[NVarCharTable] AS TABLE (
    [value] NVARCHAR(MAX) NOT NULL);

And then the Stored procedure: 然后是存储过程:

CREATE PROCEDURE [dbo].[MyProc] 
    @listArgument NVarCharTable READONLY
AS
BEGIN

    SELECT *
    FROM FOO
    WHERE Var.Id IN (Select [value] FROM @listArgument)

END

Reference: https://docs.microsoft.com/en-us/dotnet/framework/data/adonet/sql/table-valued-parameters 参考: https//docs.microsoft.com/en-us/dotnet/framework/data/adonet/sql/table-valued-parameters

If you are using SQl SERVER 2016 or above you can use the string_split function to convert the csv params into table and then use it in your IN list 如果您使用的是SQl SERVER 2016或更高版本,则可以使用string_split函数将csv参数转换为表格,然后在IN列表中使用它

eg 例如

SELECT * FROM TBL WHERE Var.A = @Param AND Var.Id IN (SELECT value FROM STRING_SPLIT(@inlist, ','))

Hope this helps 希望这可以帮助

To piggy back off of @lostmylogin, you can pass in a parameter delimited and use one of these SQL functions to parse it into a table: 要从@lostmylogin中退回,您可以传入一个分隔的参数,并使用其中一个SQL函数将其解析为一个表:

http://sqlservercentral.com/scripts/SUBSTRING/124330 or http://sqlservercentral.com/scripts/Miscellaneous/31913 http://sqlservercentral.com/scripts/SUBSTRING/124330http://sqlservercentral.com/scripts/Miscellaneous/31913

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM