In the following code, I would like to insert or update rows in an SQL table through F#.
It takes a matrix of tuple representing users and an associated scores (usrID,score) which are the results of some F# calculations.
Now I want to update a SQL table called UserScoresTable.
The code I wrote is working but is very slow.
let cnn = new System.Data.SqlClient.SqlConnection(ConfigurationManager.ConnectionStrings.Item("Database").ConnectionString)
cnn.Open()
// Definition d'une fonction qui execute une demande sous MySQL
let execNonQuery s =
let comm = new System.Data.SqlClient.SqlCommand(s, cnn, CommandTimeout = 10)
comm.ExecuteNonQuery() |> ignore
// Definition d'une fonction qui utilise les éléments d'une matrice pour updater une table dans MySQL
let updateMySQLTable (m : Matrix<float * float>) =
for j in 0 .. (snd m.Dimensions) - 1 do
for i in 1 .. (fst m.Dimensions) - 1 do
// first check if the user and score and date do not exist
sprintf "IF NOT EXISTS (SELECT * FROM ProductScores WHERE UserID = %f AND ProductID = %f) INSERT INTO ProductScores (UserID, Score, Date) VALUES (%f, %f,CURRENT_TIMESTAMP)" (fst m.[i, j]) (snd m.[i, j])
|> execNonQuery
// otherwise update the row
sprintf "UPDATE ProductScores SET Score = %f, Date = CURRENT_TIMESTAMP WHERE UserID = %f " (snd m.[i, j]) (fst m.[i, j])
|> execNonQuery
I would like to avoid the two execNonQuery requests in the code by using a stored procedure such as
CREATE PROCEDURE updateScoreByUsers
-- Add the parameters for the stored procedure here
@UserID int,
@Score float
AS
BEGIN
IF NOT EXISTS
(SELECT * FROM ProductScores WHERE UserID = @UserID )
INSERT INTO
ProductScores (UserID, Score, Date) VALUES (@UserID,@Score,CURRENT_TIMESTAMP)
ELSE
UPDATE ProductScores
SET Score = @Score, Date = CURRENT_TIMESTAMP
WHERE UserID = @UserID
END
GO
But I don’t know how to call a SQL stored procedure in F#.
How can I call it with F#?
DO you see any other way of improvements?
Set
SqlCommand.CommandTextto the name of the stored procedure and setCommandTypetoStoredProcedure. For exampleIf you’re on 2008 you may want to look into the
MERGEstatement.To significantly improve performance you need to avoid making a database call for each item. Perhaps use
SqlBulkCopyto load all the data to the server at once (use a temp table or designated staging table), then use set-based operations (UPDATE/INSERT/MERGE) to merge with your target table.