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 !!
Related
I need to insert null values in integer and string columns but in the data set that it obtains before obtaining values "---" for the case of string and "NA" for the case of INT, necessary when you have those values are inserted as void I'm using SQL Sever and my query is like that.
INSERT INTO BOEMIC01
(MICRO_DATE, MICRO_YEAR, MICRO_MONTH, MICRO_WEEK, MICRO_DIVISION, MICRO_SUBDIVISION, MICRO_CODE_COUNTRY, MICRO_COUNTRY, MICRO_CODE_CENTER, MICRO_CENTER, MICRO_FREQ, MICRO_TOTAL_M, MICRO_TOTAL_Y, MICRO_TOTAL_Z, MICRO_ID_PROCESS, MICRO_DESC_PROCESS, MICRO_TOTAL_A, MICRO_TOTAL_B, MICRO_TOTAL_C, MICRO_ID_POINT, MICRO_DESC_POINT, MICRO_CODE_MATERIAL, MICRO_DESC_MATERIAL, MICRO_TOTAL_D, MICRO_TOTAL_E, MICRO_TOTAL_F) VALUES
(
'2019-01-15',
'2019',
'1',
'3',
'X',
'Y',
'P001',
'USA',
'USA1',
'USA2',
'Daily',
'2',
'2',
'0',
'158',
'Enva',
'2',
'2',
'0',
'344',
'2',
'---', --NULL
'---', --NULL
'NA', --NULL
'NA', --NULL
'NA' --NULL
)
To insert NULL values use the NULL keyword. As in:
insert into t (col)
values (null);
To insert the default value, which is usually null, just leave the column out of the column list entirely:
insert into t (col1)
values ('happy value');
col2 will be set to its default value -- which is NULL if no other default is defined.
If you are inserting values from another source, then use try_convert() or nullif() For example:
insert into t (col_str, col_int)
values (nullif(#col_str, '---'), try_convert(int, #col_int));
Also, as a matter of standard practice, you should always use query parameters to supply any literal values to your queries, to avoid "SQL injection" issues. For instance, your query would now read:
INSERT INTO BOEMIC01
(MICRO_DATE, MICRO_YEAR, MICRO_MONTH, [...])
VALUES(?, ?, ? [...])
Notice the ? symbols and notice also that they are not in quotes.
Then, when you execute the query, you supply both the SQL string and, separately, an array of values that are to be substituted for each ? in order of occurrence. Now, SQL cannot misinterpret any value as "part of the SQL," because it isn't. Different sets of parameter values can be supplied to the same SQL string each time.
You can use functions such as NULLIF() as mentioned in BJones' comment: NULLIF('---', ?) ... the parameter's value will be passed to the NULLIF function as its second argument. I think that's a fine way to handle your requirement (and it should have been offered as "an answer").
It really depends where the values are coming from, but if for example this insert is inside a Stored Procedure and the values are coming in via parameters then the following shows how to ensure null values for the cases specified. (Irrelevant columns left out for brevity):
INSERT INTO BOEMIC01 (... MICRO_CODE_MATERIAL, MICRO_DESC_MATERIAL, MICRO_TOTAL_D, MICRO_TOTAL_E, MICRO_TOTAL_F)
select ...
, case when #MICRO_CODE_MATERIAL != '---' then #MICRO_CODE_MATERIAL else null end
, case when #MICRO_DESC_MATERIAL != '---' then #MICRO_CODE_MATERIAL else null end
, try_convert(int, #MICRO_TOTAL_D)
, try_convert(int, #MICRO_TOTAL_E)
, try_convert(int, #MICRO_TOTAL_F)
However if you are passing this data from a client application then convert it client side.
I'm having trouble with the INSERT INTO and ALTER TABLE commands. I found the following code in my notes, which indicates it probably worked at some point. However, it isn't working now. Can anyone point out mistakes?
DROP TABLE anyoung.toytable_docs;
CREATE TABLE IF NOT EXISTS anyoung.toytable_docs
(
id INT COMMENT 'unique document ID',
rev INT,
content STRING
)
COMMENT 'Employee details';
Both of the following also fail:
INSERT INTO TABLE anyoung.toytable_docs (`id`, `rev`, `content`) VALUES
('1', '1', 'The earth is flat'),
('2', '1', 'One hundred angels can dance on the head of a pin'),
('1', '2', 'The earth is flat and rests on a bull\'s horn'),
('1', '3', 'The earth is like a ball.');
use anyoung;
INSERT INTO TABLE toytable_docs (`id`, `rev`, `content`) VALUES
('1', '1', 'The earth is flat'),
('2', '1', 'One hundred angels can dance on the head of a pin'),
('1', '2', 'The earth is flat and rests on a bull\'s horn'),
('1', '3', 'The earth is like a ball.');
with: FAILED: ParseException line 1:32 cannot recognize input near 'VALUES' '(' ''1'' in select clause
When I attempt an ALTER TABLE command, both of the following failed:
ALTER TABLE anyoung.toytable_docs CHANGE content content STRING COMMENT 'The actual contents of the document';
use anyoung;
ALTER TABLE toytable_docs CHANGE content content STRING COMMENT 'The actual contents of the document';
Anyone have any insights? I already Googled/SO, etc.
The alternative is to insert from select:
with your_data as(
select stack(4,
'1', '1', 'The earth is flat',
'2', '1', 'One hundred angels can dance on the head of a pin',
'1', '2', 'The earth is flat and rests on a bull\'s horn',
'1', '3', 'The earth is like a ball.'
) as (id, rev, content)
)
use anyoung;
INSERT INTO TABLE toytable_docs
select id, rev, content from your_data;
I have a SQL script like this which I run from the command line using psql:
insert into "A"."B" values
(1, 'name=a', 'a#example.com', 'K')
How do I convert it into INSERT command inside a database?
INSERT INTO "A"."B" (first_column, second_c, third_c, fourth_1)
VALUES ('2', 'name=a', 'a#example.com.com', 'K');
Also what does "A"."B" do? I read somewhere that double quotes are needed when table name has Capitals. I seem to get an error with that when I run commands inside the database.
You said that your database name was DB and your table name was B.
You can simply use the table name alone:
INSERT INTO "B" (first_column, second_c, third_c, fourth_1)
VALUES ('2', 'name=a', 'a#example.com.com', 'K');
If you want to include the database name, then use:
INSERT INTO "DB"."B" (first_column, second_c, third_c, fourth_1)
VALUES ('2', 'name=a', 'a#example.com.com', 'K');
The double quotes are only required when the name of any entity (e.g. table, column, etc...) is a reserved word.
You can use this query where A is schema and B is table name.
INSERT INTO "A"."B" (first_column, second_c, third_c, fourth_1)
VALUES ('2', 'name=a', 'a#example.com.com', 'K');
A little hard to explain in SQL terms because I am using an in-house technology but Let's say I have an array of a structs (similar to structs we have in C#, C++, etc) and I want to insert its values in a table.
So one way is a psedu-code that iterates through the array, read the fields of the structs and inserts them into the table like this:
for int i =1 to array.Lenght
{
insert into MyTable values
{
MyTable.Field1 = array[i].Field1;
//etc ...
}
}
but this is bad, because of performnce. If array has ten elements we are calling insert method ten times.
There should be a brillinat way of doing this with just one insert, somehow using JOINS on table and just call insert one time, But I can't imagine how to do that...
Any thoughts on this are welcome.
Thanks.
Insert multiple records into MySQL with a single query:
INSERT INTO example
(example_id, name, value, other_value)
VALUES
(100, 'Name 1', 'Value 1', 'Other 1'),
(101, 'Name 2', 'Value 2', 'Other 2'),
(102, 'Name 3', 'Value 3', 'Other 3'),
(103, 'Name 4', 'Value 4', 'Other 4');
http://www.electrictoolbox.com/mysql-insert-multiple-records/
This makes sure the query is executed once. This is just an idea, avoiding multiple call insert
#sql = 'insert into mytable(col_1) values'
for int i =1 to array.Lenght
{
if(i > 1)
#sql = ',('+#sql + array[i].Field1+')'
else
#sql = '('+#sql + array[i].Field1+')'
}
#sql = #sql + ';'
exec #sql
Script looks like
insert into mytable(col_1) values
(1),(2),(3);
insert into tour_concerts values
('1', to_date('02/08/1974', 'DD/MM/YYYY'), 'Misc Concerts', 'UK'),
insert into tour_concerts values
('2', to_date('01/01/1977', 'DD/MM/YYYY'), 'The Hoople North America Your', 'USA'),
insert into tour_concerts values
('3', to_date('05/09/1971', 'DD/MM/YYYY'), 'Sheer Heart Attack UK tour', 'UK'),
insert into tour_concerts values
('4', to_date('09/02/1972', 'DD/MM/YYYY'), 'Works Japan tour', 'Japan'),
insert into tour_concerts values
('5', to_date('03/10/1975', 'DD/MM/YYYY'), 'Magic Tour', 'UK'),
insert into tour_concerts values
('6', to_date('02/01/1974', 'DD/MM/YYYY'), 'Freddie Mercury Tribute Concert for AIDS Awareness', 'UK');
SQL> #tour_concerts1;
('6', to_date('02/01/1974', 'DD/MM/YYYY'), 'Freddie Mercury Tribu
te Concert for AIDS Awareness', 'UK')
*
ERROR at line 2:
ORA-12899: value too large for column "S3327043"."TOUR_CONCERTS".
"TYPE" (actual: 50, maximum: 30)
Can someone help me fix this error?
OKAY I'VE FIXED IT
This error is clearly stating that you're trying to insert a too long varchar value in the 3rd column of the tour_concerts table.
You can fix this by:
Altering the table's structure to make the column accept more than 30 characters. For instance, 50 is the number of characters of the statement that is failing.
alter table tour_concerts modify column_name varchar2(50)
Use the Oracle substr function:
`insert into tour_concerts values ('6', to_date('02/01/1974', 'DD/MM/YYYY'), substr('Freddie Mercury Tribute Concert for AIDS Awareness', 0, 30), 'UK');
If these records are inserted thorugh an application via jdbc for instance, trim user input to not exceed your table's maximum sizes.
Error is clear: TOUR_CONCERTS.TYPE field allows 30 chars, no more, and you're trying to insert a longer string.
You have two ways to solve this:
Shorten string you're inserting (Freddie Mercury Tribute Concert for AIDS Awareness is longer than 30 chars)
Change your table definition and set TOUR_CONCERTS.TYPE field length to an higher value (say 200?)
Huh.I think you should alter your table.30 is too short.
If your DB is oracle:
alter table YOURTABLE alter column 'S3327043' varchar(100)
Check this article it seems your trying to insert longer value than the field, make the fields bigger than the maximal value you could need.