« Write code for the next developer….Because it might be you. {Or worse, your boss} | Main | SSRS Formatting output »
Thursday
Sep102009

SQL Output Clause into a table variable with more columns then the output

It turns out that if you are trying to use an output clause to insert data into a table variable / temp table and the number of fields in the table variable is greater then the number of fields you are actually using in the output clause an error will be raised. To solve this problem you will have to output a NULL or default value for the missing columns in the output clause.

DECLARE @NewPreson TABLE(
	  ID_Person		BIGINT NOT NULL
	, [RS]			UNIQUEIDENTIFIER NOT NULL
	, ID_Person_tmp	BIGINT NULL
)

INSERT INTO dbo.Person (
	  [First Name]
	, [Last Name]
	, [MI]
	, [Birth Date]
	, [RS]
        )
OUTPUT 
	  INSERTED.ID_Person -- Identity column
	, INSERTED.[RS]
	, NULL -- Needed to make the column count match
INTO 
	@NewPreson	
SELECT 
	  [First Name]
	, [Last Name]
	, [MI]
	, [Birth Date]
	, [RS]
FROM 
	#Staging Stg

that's it

Reader Comments

There are no comments for this journal entry. To create a new comment, use the form below.

PostPost a New Comment

Enter your information below to add a new comment.

My response is on my own website »
Author Email (optional):
Author URL (optional):
Post:
 
All HTML will be escaped. Hyperlinks will be created for URLs automatically.