Insert statements fail when run against SQL Server 2008 - vb.net

I have to deploy my VB.NET application developed in VB.NET and Visual Studio 2005. The customer is using SQL Server 2008, while the application is being built against SQL Server 2000.
I received the following error against SQL Server 2008:
An explicit value for identity column in 'Outgoing_Invoice' table can only be specified when column list is used and Identity Insert is ON
Here is my query for inserting data in two tables:
Dim cmd1 As New SqlCommand("Insert into Stock values(#invoice_no, #gate_pass, #exp_no, #clm_no, #category, #item_name, #weight, #units_case, 0, 0, #crtns_removed, #pieces_removed, 0, 0, #date_added, #date_removed, #inc_total_price, #out_total_price, #discount, #amount, 'Sold', #expiry_date) Insert into Outgoing_Invoice values(#invoice_no, #exp_no, #party_name, #party_code, #city, #contact, #category, #item_name, #weight, #units_case, #crtns_issued, #pieces_issued, #crtns_removed, #pieces_removed, 0, 0, #scheme, #unit_price, #out_total_price, #discount, #amount, #date_removed, #expiry_date, #order_booker, #salesman)", con)
The error message is shows at cmd1.executenonquery. Both these tables Stock and Outgoing_Invoice have an identity column labelled serial before #invoice.
The problem only arose when insert was tried on SQL Server 2008. When run against SQL Server 2000, it works as expected.
What can be the possible reason for this issue and how can it be resolved?

Your INSERT query needs to specify the column names before the VALUES clause otherwise these will be attempted in column order as defined in the DB (which is subject to change - this is not fixed).
Since you are getting an error it appears that the INSERT tries to insert into the identity column.
In general - when not inserting to all columns, you must specify column names. I would always specify column names as best practice.
So - specify a column list:
INSERT INTO aTable
(col1, col2)
VALUES
(#val1, #val2)

The insert into Outgoing_Invoice has one to many parameters.
This will work just fine. Values 1 and 2 goes to C1 and C2 and ID is assigned automatically.
declare #T table
(
ID int identity,
C1 int,
C2 int
)
insert into #T values (1, 2)
This will give the exact error you have
insert into #T values (1, 2, 3)
Check the table structure in your SQL Server 2000. It probably have one extra field. That would explain why it is working there.

You should specify fields list explicitly if you want to modify/insert IDENTITY column values of table.
Ie. your query should look like that:
Insert into Stock
(
here,
comes,
your,
real,
column,
names
)
values
(
#invoice_no,
#gate_pass,
#exp_no,
#clm_no,
#category,
#item_name,
#weight,
#units_case,
0,
0,
#crtns_removed,
#pieces_removed,
0,
0,
#date_added,
#date_removed,
#inc_total_price,
#out_total_price,
#discount,
#amount,
'Sold',
#expiry_date
)
Insert into Outgoing_Invoice
(
here,
comes,
your,
real,
column,
names,
too
)
values
(
#invoice_no,
#exp_no,
#party_name,
#party_code,
#city,
#contact,
#category,
#item_name,
#weight,
#units_case,
#crtns_issued,
#pieces_issued,
#crtns_removed,
#pieces_removed,
0,
0,
#scheme,
#unit_price,
#out_total_price,
#discount,
#amount,
#date_removed,
#expiry_date,
#order_booker,
#salesman
)

Related

Insertion of dynamic values to specific colums using SQL

I'm trying to insert a new row into a table, but one column's value insertion is dependent on a specific rule.
So far I get an error because SQL doesn't support my way and I have no idea what to do:
INSERT INTO RNFIL170
VALUES ('somthing1',0, 0, null,null,0, select max(RNFIL170.SEDER_HATZAGA)+1 from RNFIL170 , 0 , 0,1, 'somthing2');
How can I insert the max(RNFIL170.SEDER_HATZAGA)+1 into RNFIL170 ?
use INSERT INTO ... SELECT.. synxtax
Always specify the column list in the destination table
INSERT INTO RNFIL170 ( {column name list} )
SELECT 'somthing1',0, 0, null,null,0, max(RNFIL170.SEDER_HATZAGA)+1, 0 , 0,1, 'somthing2'
FROM RNFIL170 ;

Missing Semicolon at the end of sql statement Access

I am trying to execute the following code. However, I continue to recieve the following 'Missing semicolon (;) at the end of SQL statement error in Microsoft Access.
The first query creates the table with the columns defined.
create table test
(
ProcessID int,
Name varchar(10),
Address varchar(10),
RandomData varchar(10)
);
The second query is causing the missing semicolon error.
INSERT into test
VALUES (123 , 'TestName', 'TestAdd', 'qwrj3ri'),
(456 , 'TestName2', 'TestAdd', 'qwerty'),
(789 , 'TestName', 'TestAdd', 'qwrj3ri'),
(1234, 'Testing123', 'tester', 'asdfghjk');
Code with amendments per above comments to make it Access friendly & remove typos:
INSERT INTO test ( ProcessID, Name, Address, RandomData)
VALUES (123 , 'TestName', 'TestAdd', 'qwrj3ri');
INSERT INTO test ( ProcessID, Name, Address, RandomData)
VALUES (456 , 'TestName2', 'TestAdd', 'qwerty');
INSERT INTO test ( ProcessID, Name, Address, RandomData)
VALUES (789 , 'TestName', 'TestAdd', 'qwrj3ri');
INSERT INTO test ( ProcessID, Name, Address, RandomData)
VALUES (1234, 'Testing123', 'tester', 'asdfghjk');
Useful reference: https://msdn.microsoft.com/en-us/library/bb243852(v=office.12).aspx
Specific comments:
#Damien_The_Unbeliever:
I don't think access supports multiple rows in the values.
Amended to include an insert into per row instead of a value set per row (values (...), (...)).
#Thomas Tschernich:
our missing single quote next to the end of your insert
Changed 'tester', sdfg') to 'tester', 'sdfg');
#JohnLBevan:
superfluous character on end of first set of values
Changed 'qwrj3ri'), T to 'qwrj3ri'),
You can insert multiple rows in one insert statement in SQL server,but in MS ACCESS its not possible as above listed.
More techniques on multiple inserts in access are described
beautifully here

Set Identity ON with a merge statement

I am inserting and deleting elements in a table, as a result, when I want to insert a new element, it takes a new id number, but this id is not taking the last id+1. For example: the last id is 5 and I inserted a 5 elements and deleted after that, the new id will take the value of 11, and I need 6. Here is my code
CREATE TABLE #FC
(
Code varchar(25),
Description varchar(50),
Category varchar(10),
CreatedDate datetime,
LastModifiedDate datetime
);
--Adding just one record
INSERT INTO #FC (Code, Description, Category, CreatedDate, LastModifiedDate)
VALUES ('DELETE_MEMBER', 'Delete Member', 'POLICY', #Now, #Now);
;
SET IDENTITY_INSERT [dbo].[Function_Code] ON;
MERGE
INTO [dbo].[Function_Code] AS T
USING #FC AS S
ON (T.Code = S.Code) AND (T.Description = S.Description) AND(T.Category = S.Category)
WHEN MATCHED THEN
UPDATE SET
[Code] = S.[Code]
, [Description] = S.Description
, [Category] = S.Category
, [CreatedDate] = S.CreatedDate
, [LastModifiedDate] = S.LastModifiedDate
WHEN NOT MATCHED THEN
INSERT (Code, Description, Category, CreatedDate, LastModifiedDate)
VALUES(S.Code, S.Description, S.Category, S.CreatedDate, S.LastModifiedDate)
;
SET IDENTITY_INSERT [dbo].[Function_Code] OFF;
An identity is a technical field that you should not handle yourself. If you want to manage the sequence yourself, then don't use an identity field.
Nevertheless, if you really want to do it, you'll have to reseed the table to the desired value :
DELETE YourTable
DECLARE #n INT;
SELECT #n = MAX(YourId) FROM YourTable
DBCC CHECKIDENT ('YourTable', RESEED, #n)
INSERT YourTable
What you are asking is dangerous. If you make a column an identity column, don't touch it, let sql server do its job. Otherwise you can start getting primary key errors. The identity column is ready to insert 11. You insert six through eleven in your code by running it multiple time and you can get a primary key error next time the identity tries to insert a row into the table.
As Thomas Haratyk said you can reseed your table. Or you can use:
select MAX(YourId) + 1 FROM YourTable
and insert that into your identity column if you are sure you will always insert an id that has already been used by the identity column.
However, if you are commonly overwriting the default identity behavior, it may be better to manage this column yourself because deleting from an identity column results in gaps by default.

How to Update, Insert, Delete in one MERGE query in Sql Server 2008?

I have two tables - the source and the destination. I would like to merge the source into the destination using the MERGE query (SQL Server 2008).
My setup is as follows:
Each destination record has three fields (in a real application there are more than 3, of course) - id, checksum and timestamp.
Each source record has two fields - id and checksum.
A source record is to be inserted into the destination if there is no destination record with the same id.
A destination record will be updated from the source record with the same id provided the source record checksum IS NOT NULL. It is guaranteed that if the checksum IS NOT NULL then it is different from the respective destination checksum. This is a given.
A destination record will be deleted if there is no source record with the same id.
This setup should lend itself quite well to the MERGE statement semantics, yet I am unable to implement it.
My poor attempt is documented in this SQL Fiddle
What am I doing wrong?
EDIT
BTW, not MERGE based solution is here.
create table #Destination
(
id int,
[Checksum] int,
[Timestamp] datetime
)
create table #Source
(
id int,
[Checksum] int
)
insert #Destination
values (1, 1, '1/1/2001'),
(2, 2, '2/2/2002'),
(3, 3, getdate()),
(4, 4, '4/4/2044')
insert #Source
values (1, 11),
(2, NULL),
(4, 44);
merge #destination as D
using #Source as S
on (D.id = S.id)
when not matched by Target then
Insert (id, [Checksum], [Timestamp])
Values (s.id, s.[Checksum], Getdate())
when matched and S.[Checksum] is not null then
Update
set D.[Checksum]=S.[Checksum],
D.[Timestamp]=Getdate()
when not matched by Source then
Delete
Output $action, inserted.*,deleted.*;
select *
from #Destination

Not in In SQL statement?

I have set of ids in excel around 5000 and in the table I have ids around 30000. If I use 'In' condition in SQL statment I am getting around 4300 ids from what ever I have ids in Excel. But If I use 'Not In' with Excel id. I have getting around 25000+ records. I just to find out I am missing with Excel ids in the table.
How to write sql for this?
Example:
Excel Ids are
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
Table has IDs
1,
2,
3,
4,
6,
8,
9,
11,
12,
14,
15
Now I want get 5,7,10 values from Excel which missing the table?
Update:
What I am doing is
SELECT [GLID]
FROM [tbl_Detail]
where datasource = 'China' and ap_ID not in (5206896,
5206897,
5206898,
5206899,
5117083,
5143565,
5173361,
5179096,
5179097,
5179150)
Try this:
SELECT tableExcel.ID
FROM tableExcel
WHERE tableExcel.ID NOT IN(SELECT anotherTable.ID FROM anotherTable)
Here's an SQL Fiddle to try this: sqlfiddle.com/#!6/31af5/14
You're probably looking for EXCEPT:
SELECT Value
FROM #Excel
EXCEPT
SELECT Value
FROM #Table;
Edit:
Except will
treat NULL differently(NULL values are matching)
apply DISTINCT
unlike NOT IN
Here's your sample data:
declare #Excel Table(Value int);
INSERT INTO #Excel VALUES(1);
INSERT INTO #Excel VALUES(2);
INSERT INTO #Excel VALUES(3);
INSERT INTO #Excel VALUES(4);
INSERT INTO #Excel VALUES(5);
INSERT INTO #Excel VALUES(6);
INSERT INTO #Excel VALUES(7);
INSERT INTO #Excel VALUES(8);
INSERT INTO #Excel VALUES(9);
INSERT INTO #Excel VALUES(10);
declare #Table Table(Value int);
INSERT INTO #Table VALUES(1);
INSERT INTO #Table VALUES(2);
INSERT INTO #Table VALUES(3);
INSERT INTO #Table VALUES(4);
INSERT INTO #Table VALUES(6);
INSERT INTO #Table VALUES(8);
INSERT INTO #Table VALUES(9);
INSERT INTO #Table VALUES(11);
INSERT INTO #Table VALUES(12);
INSERT INTO #Table VALUES(14);
INSERT INTO #Table VALUES(15);
Import your excel file into SQL Server using the Import Data Wizard found in SQL Server Management Studio.
Then you can write the following query to find any IDs which are in the file but not in the table:
SELECT id
FROM imported_table
WHERE id NOT IN (SELECT id FROM db_table)
You should move excel data to a table in SQL Server, and then do the query in SQL Server.
select distinct id from Excel where id not in (select your ids from Sqltable)
(Obviously select your ids from Sqltable is a select which returns the Ids existing on SQL Server).
You may think that moving data to SQL Server is hard to do, but, on the contrary, it's very easy:
1) create a table
CREATE TABLE ExcelIds (Id int)
2) add a new column in excel with the following formula:
="insert into ExcelIds values(" & XX & ")"
where XX is the reference to the cell in the column with excel Ids.
3) copy the "inserts" from Excel into SSMS or whatever tool you're usin in SQL Server, and execute them.
Now you have 2 tables in SQL Server, so that querying it is absolutely easy.
When you're over, just drop the table
DROP TABLE ExcelIds
NOTE: I didn't create a key on SQL Server table because I suppose that the Ids can be repeated. Neither is justified to create a more complex SQL Query to avoid duplicates in ExcelIds for this ad hoc solution.