Inserting data using SQL Server Management Studio - sql

I am trying to use the following syntax to insert information into a database:
INSERT [dbo].[Catalog] ([CatalogID], [CatalogName], [CatalogLastUpdated], [CatalogMediaType], [CatalogComment])
VALUES (0, N'Important Info', CAST(0x00009F9700FC30F0 AS DateTime), N'Folder', N'lsafjalsdkf')
But I get the following error:
Msg 544, Level 16, State 1, Line 1
Cannot insert explicit value for identity column in table 'Catalog' when IDENTITY_INSERT is set to OFF.
I'm not sure what I'm doing wrong,..

Don't specify a value for the IDs. Let the database generate values for you:
INSERT [dbo].[Catalog] ([CatalogName], [CatalogLastUpdated], [CatalogMediaType], [CatalogComment]) VALUES (N'Important Info', CAST(0x00009F9700FC30F0 AS DateTime), N'Folder', N'lsafjalsdkf')
Alternatively you can enable identity insert:
SET IDENTITY_INSERT [dbo].[Catalog] ON
-- your INSERT statements here
SET IDENTITY_INSERT [dbo].[Catalog] OFF

Related

SQL Server : newline character

I have a programming language that does not allow me to write queries on multiple lines. It has to be written all in a single line.
I am unable to send a GO command because it has to be in a new line..
So for example, this does not work:
insert into mytable (field1, filed2) values (1, 2), (3, 4); go
as it should be
insert into mytable (field1, filed2) values (1, 2), (3, 4);
go
I've tried multiple things but none worked:
insert into mytable (field1, filed2) values (1,2),(3,4); \r go
insert into mytable (field1, filed2) values (1,2),(3,4); \r\n go
insert into mytable (field1, filed2) values (1,2),(3,4); $r$n go
insert into mytable (field1, filed2) values (1,2),(3,4); char(10) go
insert into mytable (field1, filed2) values (1,2),(3,4); char(13) go
Is there a way to write it inline, and have SQL Server use it as 2 different lines?
GO is not part of the TSQL language. It is used and recognized only by SSMS and sqlcmd to cut your script into parts ("batches"), and then each part is compiled and run separately, one after the other.
The reason that SSMS and sqlcmd work this way this is that it makes it possible to have e.g. a CREATE TABLE statement, followed by INSERT statements for that table. The INSERT-part will only compile if the table already exists, and that will be the case only after the CREATE has been run.
It is OK to combine multiple INSERTs into one statement. When in doubt about where the next statement should start, you can add a semicolon (;) to mark the end of the previous statement.

Tsql Inserting Unordered Sequence

I'm trying to insert an unordered sequence (list) into 2 kind of table explained here:
Table has one INT column
Table has several columns, one of them is an INT column (which I will use to insert the data)
So, here is the example;
List; (1, 3, 55, 3, 56456, 45)
Table; (Value INT)
I'm not looking for any solution, but a solution which is not including 'parse, split etc.' operations.
Expected solution:
INSERT INTO Table(Value)
VALUES(anyList)
Expected solution 2:
INSERT INTO Table(Value)
VALUELIST(anyList)
OR
INSERT INTO Table(Value)
VALUETABLE(anyList)
You can't directly insert like following.
INSERT INTO Table(Value)
VALUES (1, 3, 55, 3, 56456, 45)
You will get following error.
Msg 110, Level 15, State 1, Line 1 There are fewer columns in the
INSERT statement than values specified in the VALUES clause. The
number of values in the VALUES clause must match the number of columns
specified in the INSERT statement.
SQL Server will only accept your Insert if you give like following.
INSERT INTO Table(Value)
VALUES (1),(3),(55), (3), (56456), (45)
If you are getting the list as a string, in that case you need to convert it into appropriate format before inserting, like following.
DECLARE #xml as xml
DECLARE #list as varchar(max)
SET #list='(1, 3, 55, 3, 56456, 45)'
set #list = REPLACE(REPLACE(#list,'(',''),')','')
SET #xml = cast(('<X>'+replace(#list,',' ,'</X><X>')+'</X>') as xml)
INSERT INTO [Table](Value)
SELECT N.value('.', 'int') as value FROM #xml.nodes('X') as T(N)

Why this insert query go into error?

I am very new to Microsoft SQL Server and I have a problem with this INSERT query that inserts a new record in a very very big table (it has many columns).
I have this query:
INSERT INTO VulnerabilityAlertDocument ([Id],
[VulnerabilityAlertId],
[SourceId],
[BugTraqID],
[Title],
[StatusID],
[CVE],
[Published],
[LastUpdated],
[Remote],
[Local],
[Credibility],
[Classification],
[Availability],
[Ease],
[Authentication],
[CVSS2_BaseScore],
[CVSS2_TemporalScore],
[CVSS2_BaseVector],
[CVSS2_TemporalVector],
[CVSS1_BaseScore],
[CVSS1_TemporalScore],
[NVD_CVSS2_BaseScore],
[NVD_CVSS2_ComponentString],
[ImpactRating],
[Severity],
[EaseofExploit],
[UrgencyRating],
[LastChange],
[ShortSummary],
[Impact],
[TechnicalDescription],
[AttackScenario],
[Exploit],
[Credit],
[URL],
[AlertStatusId],
[Type],
[DetailLevel],
[Language],
[dd])
VALUES('10000',
'10000',
'TEST',
'5',
'TEST TITLE',
'1',
'TEST CVE',
'1998-04-30 00:00:00.000',
'2007-11-05 16:32:34.000',
'TEST REMOTE',
'TEST LOCAL',
'TEST CREDIBILITY',
'TEST CLASSIFICATION',
'TEST Availability',
'TEST EASE',
'TEST Authentication',
'TEST CVSS2_BaseScore',
'TEST VSS2_TemporalScore',
'TEST CVSS2_BaseVector',
'TEST VSS2_TemporalVector',
'TEST CVSS1_BaseScore',
'TEST CVSS1_TemporalScore',
'TEST NVD_CVSS2_BaseScore',
'TEST NVD_CVSS2_ComponentString',
'2',
'3',
'10',
'7',
'TEST LastChange',
'TEST ShortSummary',
'TEST IMPACT',
'TEST TechnicalDescription',
'TEST AttackScenario',
'TEST Exploit',
'TEST Credit',
'TEST URL',
'5',
'3',
'1',
'TEST Language',
'NULL');
In which I insert a specific value into a specified column (I specify columns by the first query section, and I specify the related values by the second section of the query)
The problem is that when I try to execute the previous query I obtain the following error
Msg 544, Level 16, State 1, Line 1
Cannot insert explicit value for identity column in table 'VulnerabilityAlertDocument' when
IDENTITY_INSERT is set to OFF.
Why? What does this mean? How can I change my query to solve this problem and so insert the record in my table?
Try SET IDENTITY_INSERT VulnerabilityAlertDocument ON before INSERT
After INSERT, add SET IDENTITY_INSERT VulnerabilityAlertDocument OFF
you have an identity column then you don't have to insert the Id, you have to delete Id from your query and the value of the Id
Remove the [Id] column from the list of columns and its corresponding value '10000'. The error is due you are trying to populate a column with a value and SQL is complaining that a automated handled value just he can provide.
BTW, you don't need to quote your numeric values if that columns are of numeric type.
Use SET IDENTITY_INSERT ON before your query.
Identity columns are auto-increasing and so do not allow insertion.
You need to explicitly state that you want to insert data into the column so that SQL server allows it.
Make sure you do not insert duplicate values for this column.
The best practice is to avoid inserting values into IDENTITY column.
Remove "[ID]"
write it like that:
INSERT INTO your table name
For example:
If you have Instructor table with attributes ID, name and dept_name
Use: Insert Command like bellow
Insert Into Instructor (ID, name, dept_name) Values (11111, 'Andrea', 'Biology');
Try this and let me show you result !!

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.

Cannot set IDENTITY_INSERT in batch

Case
Currently I'm working on database seeding script, executed with sqlcmd. For example this script sample:
IF (SELECT COUNT(*) FROM Genders)=0
BEGIN
PRINT N'Seeding table Genders...'
SET IDENTITY_INSERT Genders ON
GO
INSERT INTO Genders (GenderId, Description) VALUES (0, 'Onbekend');
INSERT INTO Genders (GenderId, Description) VALUES (1, 'Vrouw');
INSERT INTO Genders (GenderId, Description) VALUES (2, 'Man');
INSERT INTO Genders (GenderId, Description) VALUES (3, 'Onzijdig');
INSERT INTO Genders (GenderId, Description) VALUES (4, 'Vrouwman');
INSERT INTO Genders (GenderId, Description) VALUES (5, 'Manvrouw');
SET IDENTITY_INSERT Genders OFF
END
GO
Problem
However, if I execute it with sqlcmd mode in SQL Server Management Studio, it gives me this errors:
Msg 102, Level 15, State 1, Line 5 Incorrect syntax near 'ON'.
Msg 102, Level 15, State 1, Line 10 Incorrect syntax near 'END'.
Googled some, but can't figure out what I'm doing wrong. Without the IF/BEGIN/END if does work, but I like to perform the check first.
Questions:
Anything I'm doing wrong?
If impossible, any workaround available?
Thanks in advance!!
You cannot have GO within BEGIN and END. Try following
SET IDENTITY_INSERT Genders ON
IF (SELECT COUNT(*) FROM Genders)=0
BEGIN
PRINT N'Seeding table Genders...'
INSERT INTO Genders ...
END
SET IDENTITY_INSERT Genders OFF
GO