Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the current user in SQL Server stored procedure

I have a SQL Server 2008 Express R2 instance authenticating from Active Directory. Users have records associated with their AD account stored in a database. I would like to have stored procedures for them to retrieve their records.

So the procedure might make the query SELECT * FROM PurchaseOrders WHERE uid = $userid

How do I find out $userid, a property in their AD profile?

Thanks!

like image 946
Mr. Wily Avatar asked Jul 09 '11 13:07

Mr. Wily


2 Answers

Typically, you'd want to get the

SELECT SUSER_NAME()

from SQL Server - that's the connected user in DOMAIN\UserName format.

You don't typically have direct access to AD from a SQL Server machine to grab some bits from there.... if you can't work with the DOMAIN\User Name value, your best bet would be to pass in that information from your calling application to your stored procedure.

like image 120
marc_s Avatar answered Nov 06 '22 13:11

marc_s


SELECT * FROM PurchaseOrders WHERE uid = CURRENT_USER

or

SELECT * FROM PurchaseOrders WHERE uid = SUSER_NAME()
like image 38
malinois Avatar answered Nov 06 '22 15:11

malinois