23 November,2021 by Tom Collins
Question: I'm trying to capture a stored procedure output into a temporary table , which I can do using the INSERT INTO EXEC method. But I need to add an extra column to the target table , for some extra data.
The error message I get is :
Column name or number of supplied values does not match table definition.
What method can I use to execute the stored procedure and INSERT the data , along with the extra data to go into an extra column?
Answer: A method I've used previously , is to store the initial execute stored procedure output into a Table variable and run a second INSERT statement adding the extra data .
Let me use an example to illustrate the technique.
In this example - creating both a table variable and a table . After the data is added to the table variable , I append the extra data to the second INSERT
--declare a table variable , which will store the values from the initial EXEC DECLARE @SpServerDiagnosticsResult_Tmp TABLE ( create_time DateTime, component_type sysname, component_name sysname, state int, state_desc sysname, data xml ) --the permanent tables CREATE TABLE SpServerDiagnosticsResult ( create_time DateTime, component_type sysname, component_name sysname, state int, state_desc sysname, data xml, server_name varchar(50) ) --the first INSERT and store the record into the table variable INSERT INTO @SpServerDiagnosticsResult_Tmp EXEC sp_server_diagnostics; --store both the table variable data and extra column data e.g @@SERVERNAME INSERT INTO SpServerDiagnosticsResult SELECT create_time, component_type , component_name ,state ,state_desc ,data, @@SERVERNAME FROM @SpServerDiagnosticsResult_Tmp
Read More INSERT fun
Powershell insert into sql table
INSERT SELECT into existing table
This is only a preview. Your comment has not yet been posted.
As a final step before posting your comment, enter the letters and numbers you see in the image below. This prevents automated programs from posting comments.
Having trouble reading this image? View an alternate.
Posted by: |