简体   繁体   English

如何在fsharp.data.sqlclient中使用SQL IN语句?

[英]How to use SQL IN statement in fsharp.data.sqlclient?

I have the following sample code. 我有以下示例代码。 The objective is to run SQL statement with multiple input parameters. 目标是使用多个输入参数运行SQL语句。

[<Literal>]
let connectionString = @"Data Source=Localhost;Initial Catalog=Instrument;Integrated Security=True"
[<Literal>]
let query = "SELECT MacroName, MacroCode FROM Instrument WHERE MacroCode IN (@codeName)"

type MacroQuery = SqlCommandProvider<query, connectionString>
let cmd = new MacroQuery()
let res = cmd.AsyncExecute(codeName= [|"CPI";"GDP"|]) |> Async.RunSynchronously

However, codeName is inferred to be string type instead of an array or list and give me an error. 但是,codeName被推断为字符串类型而不是数组或列表,并给我一个错误。

Alternatively, I could run the query without where statement and filter based on the result. 或者,我可以在没有where语句的情况下运行查询,并根据结果过滤。 However, in lots of other cases that returns millions of rows, I would prefer filter data at the SQL server level to be more efficient. 但是,在很多其他返回数百万行的情况下,我更希望SQL服务器级别的过滤数据更有效。

I didn't find any relevant samples on the documentation of fsharp.data.sqlclient. 我没有在fsharp.data.sqlclient的文档中找到任何相关的示例。 Please help! 请帮忙!

“请参阅文档中的表值参数(TVP)”部分: http//fsprojects.github.io/FSharp.Data.SqlClient/configuration%20and%20input.html

If you have an upper bound n on the values in the IN list, you could just make n parameters. 如果IN列表中的值有上限n ,则可以只生成n个参数。 If that's unmanageable, I'm afraid the TVP suggestion is your best option. 如果这是无法管理的,我担心TVP的建议是你最好的选择。 The reason the FSharp.Data.SqlClient library is unlikely to ever support this directly is because the types are generated based on results from sp_describe_undeclared_parameters ; FSharp.Data.SqlClient库不太可能直接支持这一点的原因是因为类型是根据sp_describe_undeclared_pa​​rameters的结果生成的; there's no T-SQL parser. 没有T-SQL解析器。 We had a single digit upper bound in this scenario and were loathe to change the database, so this option worked for us. 在这种情况下我们有一个数字上限,并且不愿意更改数据库,所以这个选项对我们有用。

You can use STRING_SPLIT to abstract away the use of table-valued parameters. 您可以使用STRING_SPLIT抽象出表值参数的使用。 It seems you have to also declare the param first. 看来你必须先声明这个参数。

DECLARE @param varchar(1000) = @commaSeparatedList
SELECT Col1 FROM MyTable
WHERE Col2 IN (
  SELECT value FROM STRING_SPLIT(@param, ',')
)

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

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