I want to add some custom attributes in SqlServer connection string, something like this:
Integrated Security=SSPI;Extended Properties="SomeAttr=SomeValue";Persist Security Info=False;Initial Catalog=DB;Data Source=SERVER
And then get that attribute in sql. for example SELECT SOME_FUNCTION('SomeAttr')
There is no generalized method to pass custom connection string attributes via Client APIs and retrieve using T-SQL. You have a number of alternatives, though. Below are a few.
Method 1: Use the Application Name keyword in the connection string to pass up to 128 characters and retrieve with the APP_NAME() T-SQL function:
Note that this is limited to 128 characters and you will need to parse the payload. Also, since ADO.NET creates a separate connection pool for each distinct connection string, consider there will effectively be little or no database connection pooling.
Method 2: Execute a SET CONTEXT_INFO after connect and assign up to 128 bytes that can be retreived with the CONTEXT_INFO) T-SQL function:
Note that this is limited to 128 bytes and you will need to parse the payload.
Method 3: Create a session-level temporary table after connect and insert name/value pairs that can be retrieved with a SELECT query:
Note that you can increase the attribute value size and type as needed, and no parsing is needed.
Method 4: Create a permanent table keyed by session id and attribute name, insert name/value pairs after connect that can be retrieved with a SELECT query:
Note that you can increase the attribute value size and type as needed, and no parsing is needed.
EDIT:
Method 5: Use stored procedure sp_set_session_context to store session-scoped name/value pairs and retrieve the values with the SESSION_CONTEXT() function. This feature was introduced in SQL Server 2016 and Azure SQL Database.
You can use the WSID and APP keywords in the connection string. You can read those values using the HOST_NAME() and APP_NAME() functions. See http://msdn.microsoft.com/en-us/library/ms130822.aspx for details.