Insertion of dynamic values to specific colums using SQL - 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 ;

Related

How to insert values into a postgres table using for loop?

I have a script like this in postgres
begin;
INSERT INTO "schema"."table"(price, different_table_foreign_key)
VALUES
(1, 1)
end;
for testing purposes I want to fill table 100 times with the same values as seen above.
how can I do this using a for loop?
No need for a loop, you can use generate_series() for that:
INSERT INTO "schema"."table"(price, different_table_foreign_key)
select 1,1
from generate_series(1,100);
If you want a different value for each row, just use the one returned by `generate_series()
INSERT INTO "schema"."table"(price, different_table_foreign_key)
select 1, g.value
from generate_series(1,100) as g(value)

INSERT row in table a for every row in table b [duplicate]

If I have an SQL table with all default columns (e.g. identity column + any number of columns all with default values), what is the SQL statement to insert a row with no explicit values given?
insert MyTable /* ( doh, no fields! ) */
-- values( doh, no values! )
What's the trick?
This is a part of the INSERT syntax
INSERT INTO TableName DEFAULT VALUES
Read more here:
https://learn.microsoft.com/en-us/sql/t-sql/statements/insert-transact-sql
You can use the DEFAULT keyword.
The accepted answer only works for one row, not for multiple rows.
Let us assume you know how many rows to insert, but you want all default values. You cannot do the following, for instance
INSERT MyTable
SELECT DEFAULT VALUES -- Incorrect syntax near the keyword 'DEFAULT'.
FROM SomeQueryOrView;
-- or
INSERT MyTable
DEFAULT VALUES -- Incorrect syntax near the keyword 'FROM'.
FROM SomeQueryOrView;
Instead we can hack MERGE to do this
MERGE INTO myTable
USING (SELECT SomeValue FROM SomeQueryOrView) s
ON 1 = 0 -- never match
WHEN NOT MATCHED THEN
INSERT DEFAULT VALUES;
A bonus benefit is that we can OUTPUT data from columns which are not being inserted:
MERGE INTO myTable
USING (SELECT SomeValue FROM SomeQueryOrView) s
ON 1 = 0 -- never match
WHEN NOT MATCHED THEN
INSERT DEFAULT VALUES
OUTPUT inserted.Id, s.SomeValue;

Not able to insert a row in a table which has auto incremented primary key

I have a table reportFilters which has the following column names:
The reportFilterId is auto increment. I want to insert a row in the table with the script below:
IF OBJECT_ID(N'ReportFilters', N'U') IS NOT NULL
BEGIN
IF NOT EXISTS (SELECT * FROM [ReportFilters]
WHERE ReportId IN (SELECT ReportId FROM [Reports] WHERE ReportType = 'Operational Insights Command Staff Dashboard') )
BEGIN
INSERT INTO [ReportFilters] Values(1, 'SelectView', 'Select Views', 13, 'Views','Views', 'SelectView', 'a', 'b', 'c' );
END
END
GO
But I am getting the following error:
Column name or number of supplied values does not match table definition.
Can I please get help on this ? Thanks in advance.
I think the problem is on inserted columns can't match with inserted data because that will instead by your table column order which is ReportFilterId instead of ReportId
So that there are 11 columns in your table but your statement only provides 10 columns.
I would use explicitly specify for inserted columns (inserted columns start from ReportId except your PK ReportFilterId column)
INSERT INTO [ReportFilters] (ReportId,ReportFilterName,ReportFilterTitle....)
Values (1, 'SelectView', 'Select Views', 13, 'Views','Views', 'SelectView', 'a', 'b', 'c' );

SQL Server 2012 sequence

I create a table and sequence in order to replace identity in the table I use SQL Server 2012 Express but I get this error while I tried to insert data to the table
Msg 11719, Level 15, State 1, Line 2
NEXT VALUE FOR function is not allowed in check constraints, default objects, computed columns,
views, user-defined functions, user-defined aggregates, user-defined
table types, sub-queries, common table expressions, or derived
tables.
T-SQL code:
insert into Job_Update_Log(log_id, update_reason, jobid)
values((select next value for Job_Log_Update_SEQ),'grammer fixing',39);
This is my table:
create table Job_Update_Log
(
log_id int primary key ,
update_reason nvarchar(100) ,
update_date date default getdate(),
jobid bigint not null,
foreign key(jobid) references jobslist(jobid)
);
and this is my sequence:
CREATE SEQUENCE [dbo].[Job_Log_Update_SEQ]
AS [int]
START WITH 1
INCREMENT BY 1
NO CACHE
GO
Just get rid of the subselect in the VALUES section, like this:
insert into Job_Update_Log(log_id,update_reason,jobid)
values (next value for Job_Log_Update_SEQ,'grammer fixing',39);
Reference: http://msdn.microsoft.com/en-us/library/hh272694%28v=vs.103%29.aspx
Your insert syntax appears to be wrong. You are attempting to use a SELECT statement inside of the VALUES section of your query. If you want to use SELECT then you will use:
insert into Job_Update_Log(log_id,update_reason,jobid)
select next value for Job_Log_Update_SEQ,'grammer fixing',39;
See SQL Fiddle with Demo
I changed the syntax from INSERT INTO VALUES to INSERT INTO ... SELECT. I used this because you are selecting the next value of the sequence.
However, if you want to use the INSERT INTO.. VALUES, you will have to remove the SELECT from the query:
insert into Job_Update_Log(log_id,update_reason,jobid)
values(next value for Job_Log_Update_SEQ,'grammer fixing',39);
See SQL Fiddle with Demo
Both of these will INSERT the record into the table.
Try this one:
–With a table
create sequence idsequence
start with 1 increment by 3
create table Products_ext
(
id int,
Name varchar(50)
);
INSERT dbo.Products_ext (Id, Name)
VALUES (NEXT VALUE FOR dbo.idsequence, ‘ProductItem’);
select * from Products_ext;
/* If you run the above statement two types, you will get the following:-
1 ProductItem
4 ProductItem
*/
drop table Products_ext;
drop sequence idsequence;
------------------------------

Insert statements fail when run against SQL Server 2008

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
)