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

蓝咒 提交于 2019-12-08 14:54:25

问题


I have the following sample code. The objective is to run SQL statement with multiple input parameters.

[<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.

Alternatively, I could run the query without where statement and filter based on the result. 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.

I didn't find any relevant samples on the documentation of fsharp.data.sqlclient. Please help!


回答1:


"See Table-valued parameters (TVPs)" section in the documentation: http://fsprojects.github.io/FSharp.Data.SqlClient/configuration%20and%20input.html




回答2:


If you have an upper bound n on the values in the IN list, you could just make n parameters. If that's unmanageable, I'm afraid the TVP suggestion is your best option. 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; there's no T-SQL parser. We had a single digit upper bound in this scenario and were loathe to change the database, so this option worked for us.




回答3:


You can use STRING_SPLIT to abstract away the use of table-valued parameters. 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, ',')
)


来源:https://stackoverflow.com/questions/26248397/how-to-use-sql-in-statement-in-fsharp-data-sqlclient

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!