title: Dynamic SQL Query to pull Primary Key Name
body: <p>I am working on a much larger query that will build out C# functions and classes for me but I am running into issues with one small part, I need to rewrite the query below so that specifically the part "@DataBaseName.INFORMATION_SCHEMA.KEY_COLUMN_USAGE" will work. Obviously the current way it is written will not work but for the life of me I cannot figure out how to change it to get it to work. Just a quick note if I were to just type out the query with the actual DB name and DB Table name it will work but I need to be able to store both of those in variables at the beginning to accomplish the task I am looking for. This is for MS SQL Server 2008 R2</p>
  
  <pre><code>declare @TableName sysname = 'ENTERTABLENAME'
  declare @DataBaseName sysname = 'ENTERDATABASENAME'
  
  /* Start of Update Function Created */
  
  declare @PrimaryKey varchar(max) = ''
   SELECT @PrimaryKey = COLUMN_NAME FROM @DataBaseName.INFORMATION_SCHEMA.KEY_COLUMN_USAGE
  WHERE TABLE_NAME = @TableName AND CONSTRAINT_NAME LIKE 'PK%'
  </code></pre>