I'm trying to figure out if there is a way to return the primary key value, during an insert, without knowing the Primary Keys Column Name.
I would like to use Output because not all of the Primary Keys in the Database are Integers, but I do not think it is possible to do a subquery for an Output.
CREATE TABLE TestTable ( PkId INT Identity(1,1) NOT NULL, Value1 VARCHAR(50) NULL, Value2 VARCHAR(50) NULL, CONSTRAINT PkId PRIMARY KEY (PkId) ) INSERT INTO TestTable(Value1, Value2) OUTPUT INSERTED. --Primary Key to find here Values('Test', 'Test2') I was thinking about using something like this as a subquery, but like I stated before I don't think it is possible to use an output with a subquery
SELECT column_name as PRIMARYKEYCOLUMN FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS AS TC INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS KU ON TC.CONSTRAINT_TYPE = 'PRIMARY KEY' AND TC.CONSTRAINT_NAME = KU.CONSTRAINT_NAME AND KU.table_name='TestTable' ORDER BY KU.TABLE_NAME, KU.ORDINAL_POSITION; Any help would be greatly appreciated!
PkIdisNOT NULLso why you're trying to insertNULLto it?IDENTITY()what's the problem withINSERT INTO TestTable(Value1, Value2) OUTPUT INSERTED.PkId Values('Test', 'Test2')?