How to use SQL user defined functions in .NET?

前端 未结 2 1390
广开言路
广开言路 2020-12-10 06:24

I created a scalar function in the DB

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER FUNCTION [dbo].[fn_GetUserId_Username]
    (
    @Username varch         


        
2条回答
  •  渐次进展
    2020-12-10 06:43

    This is very similar to the above answer, but the below code allows you to call a UDF with any number of parameters and any return type. This might be useful as a more general solution. This also hasn't been tested thoroughly...I think it will have some problems with varchars.

    public class MyDBAccess
    {
        private SqlConnection sqlConnection = new SqlConnection("databaseconnectionstring");
    
        public int GetUserIdByUsername(string username)
        {
            int userID = CallUDF("dbo.fn_GetUserId_Username", new SqlParameter("@Username", username));
            return userID;
        }
    
        internal static T1 CallUDF(string strUDFName, params SqlParameter[] aspParameters)
        {
            using (SqlConnection scnConnection = sqlConnection)
            using (SqlCommand scmdCommand = new SqlCommand(strUDFName, scnConnection))
            {
                scmdCommand.CommandType = CommandType.StoredProcedure;
    
                scmdCommand.Parameters.Add("@ReturnValue", TypeToSqlDbType()).Direction = ParameterDirection.ReturnValue;
                scmdCommand.Parameters.AddRange(aspParameters);
    
                scmdCommand.ExecuteScalar();
    
                return (T1)scmdCommand.Parameters["@ReturnValue"].Value;
            }
        }
    
        private SqlDbType TypeToSqlDbType()
        {
            if (typeof(T1) == typeof(bool))
            {
                return SqlDbType.Bit;
            }
            else if (typeof(T1) == typeof(int))
            {
                return SqlDbType.Int;
            }
            //
            // ... add more types here
            //
            else
            {
                throw new ArgumentException("No mapping from type T1 to a SQL data type defined.");
            }
        }
    }
    

提交回复
热议问题