Read display value of a reference field
Gets related record(s) from a reference field. You need to know the referenced table name for that field, then query by sys_id (Primary Key).
Standard SQL query example
This is the base query accepted by the connector. To execute it in SQL Server, you have to pass it to the Data Gateway via a Linked Server. See how to accomplish this using the examples below.
--STEP#1 returns incident number and related company (sys_id)
SELECT number,company FROM incident
--STEP#2 find related table for company field
select name,reference from get_table_columns WITH(TableName='incident') order by 1
--STEP#3 query related table with sys_id returned in step#1
select sys_id, name from core_company where sys_id='31bea3d53790200044e0bfc8bcbe5dec'
Using OPENQUERY in SQL Server
SELECT * FROM OPENQUERY([LS_TO_SERVICENOW_IN_GATEWAY], '--STEP#1 returns incident number and related company (sys_id)
SELECT number,company FROM incident
--STEP#2 find related table for company field
select name,reference from get_table_columns WITH(TableName=''incident'') order by 1
--STEP#3 query related table with sys_id returned in step#1
select sys_id, name from core_company where sys_id=''31bea3d53790200044e0bfc8bcbe5dec''')
Using EXEC in SQL Server (handling larger SQL text)
The major drawback of OPENQUERY is its inability to incorporate variables within SQL statements.
This often leads to the use of cumbersome dynamic SQL (with numerous ticks and escape characters).
Fortunately, starting with SQL 2005 and onwards, you can utilize the EXEC (your_sql) AT [LS_TO_SERVICENOW_IN_GATEWAY] syntax.
DECLARE @MyQuery NVARCHAR(MAX) = '--STEP#1 returns incident number and related company (sys_id)
SELECT number,company FROM incident
--STEP#2 find related table for company field
select name,reference from get_table_columns WITH(TableName=''incident'') order by 1
--STEP#3 query related table with sys_id returned in step#1
select sys_id, name from core_company where sys_id=''31bea3d53790200044e0bfc8bcbe5dec'''
EXEC (@MyQuery) AT [LS_TO_SERVICENOW_IN_GATEWAY]