MS SQL Server does not let me set IDENTITY_INSERT to ON - sql

I have a table in a database (MS SQL Server 2008) that is filled with data. I want to move some of this data (among which is a column with an IDENTITY constraint) to a table with the same name in another database for back-up purposes. Since I have a table that has an IDENTITY column that I want to move, I need to set IDENTITY_INSERT to ON. I do not want to hard code this, as I may have other tables and columns in the future with this problem.
I have been fiddling with this piece of code for hours and cannot get it to work:
SET IDENTITY_INSERT FDW_test2.dbo.[MIS-ODB_INOUT_LOG] OFF
declare #IDENTITY_INSERTTableCommand nchar(150) = 'SET IDENTITY_INSERT
FDW_test2.dbo.[MIS-ODB_INOUT_LOG] ON'
execute (#IDENTITY_INSERTTableCommand)
INSERT INTO FDW_test2.dbo.[MIS-ODB_INOUT_LOG] ([INOUT_Link ID],
[INOUT_DIARY_KEY])
SELECT [INOUT_Link ID], [INOUT_DIARY_KEY]
FROM FDW.dbo.[MIS-ODB_INOUT_LOG]
WHERE [INOUT_Client ID] = '1-197'
I get the following error when running this script: An explicit value for the identity column in table can only be specified when a column list is used and IDENTITY_INSERT is ON SQL Server.
It seems that MS SQL is ignoring the 'ON' in my string #IDENTITY_INSERTTableCommand, yet it complains of synthax errors when I enter gibberish into the string.
Can anyone tell me what I am doing wrong? Thank you in advance.

Once the execute it completed the IDENTITY_INSERT will be back to OFF. It will be ON only inside the execute
Move the Insert statement to string and execute it
declare #IDENTITY_INSERTTableCommand nvarchar(2000) =
'SET IDENTITY_INSERT FDW_test2.dbo.[MIS-ODB_INOUT_LOG] ON
INSERT INTO FDW_test2.dbo.[MIS-ODB_INOUT_LOG] ([INOUT_Link ID],
[INOUT_DIARY_KEY])
SELECT [INOUT_Link ID], [INOUT_DIARY_KEY]
FROM FDW.dbo.[MIS-ODB_INOUT_LOG]
WHERE [INOUT_Client ID] = ''1-197''
'
execute (#IDENTITY_INSERTTableCommand)

Related

Pentaho MS-SQL set IDENTITY_INSERT a00 ON for table output

PDI 9.0
Simple job
MS SQL connection
Table input -> tableouput
tableouput table :
CREATE TABLE [dbo].[a00](
[ProductID] [int] NOT NULL [IDENTITY(1,1)][1]
..
I need to write IDENTITY explicitly
in SSMS I run
set IDENTITY_INSERT a00 ON
and doing insert ok.
In pentaho I got error
Table output.0 - Cannot insert explicit value for identity column in table 'a00' when IDENTITY_INSERT is set to OFF.
trying to run in SQl : set IDENTITY_INSERT a00 ON
Before
SQL -> table input -> table output
but same error
Seems set IDENTITY_INSERT a00 ON runs in DIFFerent SESSION
then table output
How can I run set IDENTITY_INSERT a00 ON in same session
or point out to use it ;
Pentaho tries to do everything in parallel while on the same Transformation. So you need to create a job and do it sequentialy
1st - SQL script "SET IDENTITY_INSERT a00 ON"
2nd - Your transformation with the table output
3th - SQL script "SET IDENTITY_INSERT a00 OFF"
Example:
Hope this helps.
I checked using profiler
SQL run in one session
transformation in another
here is problem
do not know how to resolev it
I solved this problem by adding an extra option to my database connection.
Under "Advanced" in the database connection, enter a SQL statement that will be executed right after connecting to the database.
My statement (MSSQL) looks like
set identity_insert [dbname].[schemaname].[tablename] on;
Your tablename could also be set with a variable.

A rowset based on the SQL command was not returned by the OLE DB provider

I was wondering if anyone can help me with this issue? I am calling a sproc in SSIS. All I want it to do is create a file if any new records are updated or inserted into a table. That table checks another source table to see if anything changed in that table and then adds it to the copy table, if there are any updates or changes to the source table I want a file to get created and if not we don't want it to do anything.
I have tested the logic and everything seems to work fine but once I try to run the sproc in SSIS it gives the error message, "A rowset based on the SQL command was not returned by the OLE DB provider." Initially I thought this means that it is erroring out because no rows are being returned but even when there are rows being returned I still get the very same error message. I can parse the query and preview the results in SSIS but it still turns red when run and gives that error message.
Below is the code to my sproc. Any help or ideas would be so appreciated!
USE [dev02]
GO
/****** Object: StoredProcedure [dbo].[usp_VoidReasons] Script Date: 8/25/2016 11:54:44 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*-------------------------------------------------------------------------- ----
Author: Andrej Friedman
Create date: 07/27/2016
Description: This sproc assists SSIS in creating a file but only when a new row has been added to the VoidReasonsLookup table
that didnt exist there before or if the code or description has changed in that table. The table is compared to the prod1.dbo.miscde
table for diferences and only for the Void Reasons of that table (mcmspf = 'cv').
History:
SampleCall: EXEC [dbo].[usp_VoidReasons]
--truncate table dev02.dbo.VoidReasonsLookup
--select * from dbo.VoidReasonsLookup
--update VoidReasonsLookup set Description = 'BB' where Description = 'BENEFIT CODE ADJUSTMENT'
------------------------------------------------------------------------------*/
ALTER proc [dbo].[usp_VoidReasons]
as
declare #ImportDate as date = CONVERT (date, GETDATE())
insert into VoidReasonsLookup (Code, [Description])
--Change #1 -- New Code and Description
--This will insert a new row in the VoidReasons table where the Code and description doesnt exist there but exists in the source table.
select (M.mcmscd_1 + M.mcmscd_4) as Code, mcmsds as [Description] from prod1.dbo.miscde M
left join VoidReasonsLookup VL
on M.mcmscd_1 + M.mcmscd_4 = VL.Code
where M.mcmspf = 'cv'
and VL.Code is null
--Change #2 -- Code dropped off source table so we need it gone from the VoidReasons table
--This will delete rows where the Code doesnt exists in the source table any longer
delete from VL from VoidReasonsLookup as VL
left join prod1.dbo.miscde as M
on VL.Code = M.mcmscd_1 + M.mcmscd_4
where M.mcmscd_1 + M.mcmscd_4 is null
--Change #3 -- Description has changed for a certain code in the source table.
--This will update the Description to the source table if it is different in the VoidReasons table and update the ImportDate to today when that update took place.
update VL
set VL.[Description] = M.mcmsds,
VL.ImportDate = #ImportDate
from dbo.VoidReasonsLookup as VL
join prod1.dbo.miscde as M
on VL.Code = M.mcmscd_1 + M.mcmscd_4
where VL.[Description] <> M.mcmsds
and M.mcmspf = 'cv'
--This will give back everything in the VoidReasons table but only if todays date is the same as the ImportDate column of the table.
--This will mean that today a record was inserted or updated.
If exists(select ImportDate from VoidReasonsLookup
where ImportDate = #ImportDate)
select * from VoidReasonsLookup
else
print 'no changes detected in VoidReasons table'
Add SET NOCOUNT ON and at the end you are selecting resultset basedon condition, SSIS expects resultset always based on output type which you configured. You can use empty resultset as an output will solve the problem
Comment out everything, rerun and see if you still get the error. Uncomment parts until you get the error. Once you get the error, you know what is causing the issue.

IDENTITY_INSERT error while trying to insert data into table

I want to copy data from a table named ActionType inside a database TD_EDD, into another table named ActionType inside another database DsVelocity.
I have written the following query:
INSERT INTO [DsVelocity].[dbo].[ActionType]
([ActionTypeID]
,[ActionTypeName]
,[ActiveStatus])
SELECT [ActionTypeID], [ActionType], [Active/Deactive]
FROM [TD_EDD].[dbo].[ActionType]
GO
Whenever I'm trying to do this, I'm getting the following error:
Msg 544, Level 16, State 1, Line 1
Cannot insert explicit value for identity column in table 'ActionType' when IDENTITY_INSERT is set to OFF.
I don't understand what's wrong and why I'm getting this error?
Note that I'm using Microsoft SQL Server 2008 R2.
This means that when you insert data into target table, you will have conflicting ids. Most likely ActionTypeId column
to Fix it use
INSERT INTO [DsVelocity].[dbo].[ActionType]
([ActionTypeName]
,[ActiveStatus])
SELECT [ActionType], [Active/Deactive]
FROM [TD_EDD].[dbo].[ActionType]
GO
Well, lets assume from the message that ActionTypeID is an IDENTITY Column. You cannot isert values into this column as it is auto generate, uless you use IDENTITY_INSERT
Allows explicit values to be inserted into the identity column of a
table.
At any time, only one table in a session can have the IDENTITY_INSERT
property set to ON. If a table already has this property set to ON,
and a SET IDENTITY_INSERT ON statement is issued for another table,
SQL Server returns an error message that states SET IDENTITY_INSERT is
already ON and reports the table it is set ON for.
If the value inserted is larger than the current identity value for
the table, SQL Server automatically uses the new inserted value as the
current identity value.
The setting of SET IDENTITY_INSERT is set at execute or run time and
not at parse time.
So you would have to do something like
SET IDENTITY_INSERT [DsVelocity].[dbo].[ActionType] ON
before the insert.

SQL trigger, ALTER_TABLE, need the ability to change table in another database

I have two databses, tempdblog and testdblog. I'm trying to figure out how, when i alter a table on tempdblog, that exact same command will be executed on testdblog, i don't want the rows transfered i strictly want the columns.
Below is what i have atm from a site, i've tried to add a "USE testdblog" but it errors back at me about "a USE statement is not allowed..." as well as "must declare the scalar variable #test".
The new column names could be anything, all i know is that it's not a "add this column to the end of the table", it's more like "add this column just before userdef0 column".
I store the SQL query it ran on the main database and try to re-execute it on the other table, it's just a matter of finding out how to change databases.
USE tempdblog
GO
ALTER TRIGGER [db_LOG]
ON DATABASE
FOR ALTER_TABLE
AS
SET NOCOUNT ON
DECLARE #xEvent XML
DECLARE #tests nvarchar(MAX)
SET #xEvent = eventdata()
SET #tests = CONVERT(VARCHAR(MAX), #xEvent.query('data(/EVENT_INSTANCE/TSQLCommand/CommandText)'))
exec testdblog..sp_executesql #tests;
GO
You can't have GO commands in there. Once you have a valid dynamic SQL statement constructed (you don't right now), you should also try:
EXEC testdblog..sp_executesql #test;
Or just simply:
INSERT INTO testdblog.dbo.dbLog(columns) VALUES(...);

How to turn IDENTITY_INSERT on and off using SQL Server 2008?

Why am I getting an error doing an insert when IDENTITY_INSERT is set to OFF?
How do I turn it on properly in SQL Server 2008? Is it by using SQL Server Management Studio?
I have run this query:
SET IDENTITY_INSERT Database. dbo. Baskets ON
Then I got the message back in the console that the Command(s) completed successfully.
However when I run the application, it still gives me the error shown below:
Cannot insert explicit value for identity column in table 'Baskets' when
IDENTITY_INSERT is set to OFF.
Via SQL as per MSDN
SET IDENTITY_INSERT sometableWithIdentity ON
INSERT INTO sometableWithIdentity
(IdentityColumn, col2, col3, ...)
VALUES
(AnIdentityValue, col2value, col3value, ...)
SET IDENTITY_INSERT sometableWithIdentity OFF
The complete error message tells you exactly what is wrong...
Cannot insert explicit value for identity column in table 'sometableWithIdentity' when IDENTITY_INSERT is set to OFF.
I had a problem where it did not allow me to insert it even after setting the IDENTITY_INSERT ON.
The problem was that i did not specify the column names and for some reason it did not like it.
INSERT INTO tbl Values(vals)
So basically do the full INSERT INTO tbl(cols) Values(vals)
Import:
You must write columns in INSERT statement
INSERT INTO TABLE
SELECT * FROM
Is not correct.
Insert into Table(Field1,...)
Select (Field1,...) from TABLE
Is correct
I know this is an older thread but I just bumped into this. If the user is trying to run inserts on the Identity column after some other session Set IDENTITY_INSERT ON, then he is bound to get the above error.
Setting the Identity Insert value and the subsequent Insert DML commands are to be run by the same session.
Here #Beginner was setting Identity Insert ON separately and then running the inserts from his application. That is why he got the below Error:
Cannot insert explicit value for identity column in table 'Baskets' when
IDENTITY_INSERT is set to OFF.
It looks necessary to put a SET IDENTITY_INSERT Database.dbo.Baskets ON; before every SQL INSERT sending batch.
You can send several INSERT ... VALUES ... commands started with one SET IDENTITY_INSERT ... ON; string at the beginning. Just don't put any batch separator between.
I don't know why the SET IDENTITY_INSERT ... ON stops working after the sending block (for ex.: .ExecuteNonQuery() in C#). I had to put SET IDENTITY_INSERT ... ON; again at the beginning of next SQL command string.
This is likely when you have a PRIMARY KEY field and you are inserting a value that is duplicating or you have the INSERT_IDENTITY flag set to on
Another option is where you have tables like 'type' or 'status', for example, OrderStatus, where you always want to control the Id value, create the Id (Primary Key) column without it being an Identity column is the first place.