Sql Server Ce 3.5 Identity insert

情到浓时终转凉″ 提交于 2019-12-01 06:06:48

问题


got an issue with identity columns in Sql Server CE

when using Server explorer, in VS2008, executing the following script

SET IDENTITY_INSERT testTable ON; Insert into testTable (id,name) values (1,'Something') SET IDENTITY_INSERT testTable ON;

sends the follow message error 'The Set SQL construct or statement is not supported.' but then inserts the row fine ?!?!?!

anyway, when I try to do the same thing through C#, giving that script as a command text it fails saying the error was in the "Insert key word"

I understand that against SQL SERVER CE the command only accepts one batch command at the time so in that case we have three commands (it would work with the full SQLServer) any idea?


回答1:


If you're using SqlCe 3.5 then this should work. However, you need to send it as two separate commands. You can't separate commands with ";" or "GO" in SqlCe. Rather, you need to do something like this:

            SqlCeConnection connection = new SqlCeConnection(connectionString);
            SqlCeCommand identChangeCommand = connection.CreateCommand();
            identChange.CommandText = "SET IDENTITY_INSERT SomeTable ON";
            SqlCeCommand cmd = connection.CreateCommand();
            cmd.CommandText = "INSERT INTO testTable (Id, column1, column2..) VALUES (10,val1,val2...)";
            try
            {
                connection.Open();
                identChange.ExecuteNonQuery();
                cmd.ExecuteNonQuery();
            }

            catch (SqlCeException ex)
            {
                //log ex
            }
            finally
            {
                connection.Close();
            }



回答2:


TRY

SET IDENTITY_INSERT testTable ON; 
Insert into testTable (id,name) values (1,'Something');
SET IDENTITY_INSERT testTable OFF;

OR

SET IDENTITY_INSERT testTable ON
go
Insert into testTable (id,name) values (1,'Something')
go
SET IDENTITY_INSERT testTable OFF
go


来源:https://stackoverflow.com/questions/682654/sql-server-ce-3-5-identity-insert

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!