Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server: Insert Result of WHOAMI into Table

I have a table with 2 columns, one of which I would like to insert the result of the WHOAMI command. Tried doing the following but I presume it won't work due to the different amount of columns:

UPDATE tblName 
SET colName = (xp_cmdshell 'whoami.exe') 
WHERE id = 1
like image 327
pee2pee Avatar asked Jan 19 '16 15:01

pee2pee


People also ask

How do I insert a stored procedure result into a table?

When the stored procedure returns a lot of columns and you do not want to manually "create" a temporary table to hold the result, I've found the easiest way is to go into the stored procedure and add an "into" clause on the last select statement and add 1=0 to the where clause.

How do I get output in SQL?

The OUTPUT clause returns the values of each row that was affected by an INSERT, UPDATE or DELETE statements. It even supports with a MERGE statement, which was introduced in SQL Server 2008 version. The result from the OUTPUT clause can be inserted into a separate table during the execution of the query.

How do I display a username in SQL?

SQL Server USER_NAME() Function The USER_NAME() function returns the database user name based on the specified id. If no id is specified, this function will return the name of the current user.

What does Xp_cmdshell do?

The xp_cmdshell is an extended stored procedure provided by Microsoft and stored in the master database. It allows execution of operating system commands and host executables from the T-SQL code directly in the Windows command outside the controls of database access permissions.


1 Answers

If you want the user who's logged into the database (which could be a Windows or a SQL Login), you could use the built in SUSER_NAME() function instead

UPDATE tblName set colName = SUSER_NAME() WHERE id=1

If you truly want the service account that's running the SQL Server process (which is what you'd get from whoami.exe), you may be better off using the sys.dm_server_services view, which won't require enabling xp_cmdshell (which can pose some security risks if it's not locked down properly) (note: this requires SQL Server 2008R2 SP1 at a minimum):

UPDATE tblName 
SET colName = (
    SELECT TOP 1 
       service_account 
    FROM sys.dm_server_services 
    WHERE servicename LIKE 'SQL Server (%') 
WHERE id=1

otherwise

DECLARE @output TABLE (v varchar(200))

INSERT @output (v) exec xp_cmdshell 'whoami.exe'

UPDATE tblName SET colName = (select top 1 * from @output) WHERE id=1
like image 129
Dan Field Avatar answered Oct 12 '22 23:10

Dan Field