I am attempting to insert the record into m sql database. My very first value is 1 then 1001. My insert will place the first value which is 1 correctly but 1001 and beyond it returns null. How can I change this to read the value and not use the index since it does not go in sequential order?
Insert Method:
SqlCommand addJob = new SqlCommand(#"INSERT INTO JobNumber ( JobID, CustomerID, JobDescription, IsActive) VALUES ( #JobID, (SELECT #CustomerID FROM Customer C WHERE C.CustomerID = #CustomerID), #JobDescription, #IsActive)", dbConn);
addJob.Parameters.AddWithValue("#JobID", Convert.ToInt32(jobidTextBox.Text));
addJob.Parameters.AddWithValue("#CustomerID", Convert.ToInt32(customeridComboBox.SelectedIndex) + 1);
addJob.Parameters.AddWithValue("#JobDescription", jobdescriptionTextBox.Text);
addJob.Parameters.AddWithValue("#IsActive", isactiveCheckBox.Checked);
dbConn.Open();
addJob.ExecuteNonQuery();
Try selected text/ selected item property of the combo-box instead of the index.
you should retrieve your text item like this
addJob.Parameters.AddWithValue("#CustomerID", Convert.ToInt32(customeridComboBox.Items[customeridComboBox.SelectedIndex+ 1] );
Related
I have to iterate a array with for loop to find it contains specific words in it and add that in listbox
String[] result= ["vicky","vinay#","google#","hello"]
For (l=0 ; l<= result.length; l++)
{
If(result[l].contains("#")
{
Listbox.items.add(result[l]);
}
}
What this does is it gets only first found value I am not getting second value?
You need an ordering column for your data. Let me assume that you have one.
First add the new column:
alter table t add column id int;
Note: id is a really bad name for a column that can be null. Then:
with toupdate as (
select t.*,
row_number() over (partition by col1 order by <ordering col>) as seqnum
from t
)
update toupdate
set id = (case when col1 = 1 then seqnum end);
Strictly speaking, you don't need to update the values when col1 = 0, because the default value is NULL. However, in case you want a different value there, I am leaving out the where col1 = 1.
You can simulate a partial identity column, but you won't be able to incorporate an actual IDENTITY column to the table that works conditionally.
If you just need to update a new column with an incremental value, you can just use a ROW_NUMBER() over a filtered SELECT:
;WITH CTE AS
(
SELECT
T.Col1,
T.ID,
GeneratedID = ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) -- Determine your order here
FROM
YourTable AS T
WHERE
T.Col1 IS NOT NULL
)
UPDATE C SET
ID = C.GeneratedID
FROM
CTE AS C
Your query should be like below :
update <table_name> set id=1 where Col1=1;
update <table_name> set id=null where Col1=0;
I have thought about using distinct but im not too sure how to do it as a single query for efficiency of code, is there a way? I am basically trying to check if there is already an existing data entry, I am trying to check it with BookingTime. Thanks :)
This is my SQL query:
string bookingInfo = "INSERT INTO Booking(BookingDate, BookingTime, CustomerID, EmployeeID, ServiceType, BookingLength) " +
"VALUES (#BookingDate, #BookingTime, #CustomerID, #EmployeeID, #ServiceType, #BookingLength) " +
"where not exists (SELECT 1 FROM Booking WHERE BookingTime = #BookingTime)";
The error I receive: "Additional information: Query input must contain at least one table or query."
The best way is to let the database do the checking.
Create a unique index or constraint on the table:
create unique index unq_booking_bookingtime on booking(bookingtime);
Note: this is based on your query. It seems unlikely to me that only bookingtime defines uniqueness.
The database will then generate an error if it encounters duplicates. You can prevent the error using insert ignore or insert on duplicate key update (the latter is the preferred method).
The WHERE clause is invalid is invalid in the "INSERT ... VALUES" statement shown.
MySQL does provide an "INSERT ... SELECT ..." form of the INSERT statement (which does not use a VALUES clause). The SELECT statement can have a WHERE clause, but to include a WHERE clause in a SELECT, there has to be a FROM clause. You can use an inline view (aka a derived table) to return a single row, or you could use the builtin Oracle-style dummy table DUAL to return a single row. (We don't care what columns get returned, we just need one row returned.)
For example:
INSERT INTO Booking
( BookingDate
, BookingTime
, CustomerID
, EmployeeID
, ServiceType
, BookingLength
)
SELECT #BookingDate
, #BookingTime
, #CustomerID
, #EmployeeID
, #ServiceType
, #BookingLength
FROM ( SELECT 1 ) i
WHERE NOT EXISTS
( SELECT 1
FROM Booking b
WHERE b.BookingTime = #BookingTime
)
Now the SELECT statement (which can be tested separately from the INSERT) will return either zero or one rows. And whatever row it returns will be passed to the INSERT.
As an alternative to the "NOT EXISTS" predicate, you could use an anti-join pattern:
SELECT #BookingDate
, #BookingTime
, #CustomerID
, #EmployeeID
, #ServiceType
, #BookingLength
FROM ( SELECT 1 ) i
LEFT
JOIN Booking b
ON b.BookingTime = #BookingTime
WHERE b.BookingTime IS NULL
string bookingInfo = "INSERT INTO Booking(BookingDate, BookingTime, CustomerID, EmployeeID, ServiceType, BookingLength) " +
"SELECT #BookingDate, #BookingTime, #CustomerID, #EmployeeID, #ServiceType, #BookingLength " +
" FROM Booking WHERE NOT EXISTS (SELECT * FROM Booking WHERE BookingTime = #BookingTime) LIMIT 1 "
Try this SqlFiddle
I have an table name dbo.EmpInfo having 4 columns
1-UserId 2-SubUserId 3-Year 4-Status
I have an another table (in other database) name dbo.EmpInfo1 having 4 columns
1-UserId 2-SubUserId 3-Year 4-Status
UserId may be repeating in both tables..
Now i have to find those UserId from Both tables whose Status="Success" and this status count is < 10 and bind these values in Gridview..
for ex-I have an UserId say mayank#gmail.com and in dbo.EmpInfo it has status count=5(Status="Success") and in dbo.EmpInfo1 it has status count=7 so from both tables the total count for mayank#gmail.com is 12 so we have to bind this userId in Gridview. and Gridview having all the above columns..
i have a procedure -
ALTER proc [dbo].[sp_countUserDetails]
as
begin try
begin transaction
Select distinct(UserId) from EmpInfo where Status='Success'
union all
Select distinct(UserId) from MyDB.dbo.EmpInfo1 where Status='Sucess'
commit transaction
end try
in my .cs file i used
SqlDataReader dr = ms.sp_SelectExecuter("sp_countUserDetails");
DataTable dt = new DataTable();
dt.Load(dr);
foreach (DataRow DR in dt.Rows)
{
ms = new MethodStore();
ms.sp_SelectExecuter("sp_usercount", "#userid", (DR["UserId"]).ToString());
}
and the Procedure is-
ALTER Procedure [dbo].[sp_usercount]
#userid varchar(50)
as
declare #count1213 dec =0, #count1314 dec =0;
begin try
begin transaction
select #count1314= count(UserId) from EmpInfo where Status='Status' and UserID=#userid;
select #count1213= count(UserId) from MyDB.dbo.EmpInfo1 where Status='Success' and UserID=#userid;
select #count1213+#count1314 as 'Count'
if((#count1213+#count1314)>=10)
insert into MyTaxCafe.dbo.demo values (#userid);
commit transaction
end try
bt the table dbo.demo doesn't contain distinct UserId..because our Procedure
[dbo].[sp_countUserDetails]
give Distinct values from both table but at due to Union there is an redundancy can we control it because Same UserId may be Exist in both tables
First you need a SQL to query two database , you may try it like this
SELECT Status FROM [database1].[dbo].[TableName] AS t1 INNER JOIN [database2].[dbo].[TableName] AS t2
ON (t1.UserId = t2.UserId)
WHERE Status='Success'
GROUP BY Status
Having COUNT(Status) < 10
in your C# code , use SqlDataAdapter to fill DataTable,
then set DataGridView's field DataSource = DataTable
You must use union from your query to get expected result.
Your columns are same in both tables so u can use union without any changes
for example
select * (select * from TableName1
where Status = 'Success'
union
select * from TableName2
where Status = 'Success'
) A
where count(Status)<10
group by SubUserId, Year, Status
try this.
I have this kind of method on inserting data
private void InsertReceipt()
{
decimal Stub;
Stub = Math.Floor(decimal.Parse(txtAmount.Text) / 2000);
SqlCommand cmd = new SqlCommand();
cmd.Connection = cn;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "INSERT INTO Ticket(CustomerID, Date, Store, Amount, NoStub)" +
"VALUES (#CustomerID, #Date, #Store, #Amount, #NoStub) ";
cmd.Parameters.AddWithValue("#CustomerID", txtCustomerID.Text);
cmd.Parameters.AddWithValue("#Date", dtpDate.Value.Date.ToString());
cmd.Parameters.AddWithValue("#Store", txtStore.Text);
decimal amount = decimal.Parse(txtAmount.Text);
cmd.Parameters.AddWithValue("#Amount", amount);
cmd.Parameters.Add("#NoStub", SqlDbType.Decimal).Value = Stub;
cmd.ExecuteNonQuery();
}
I just want to have a method that if you insert a data in table "Ticket" there's another table will be updating.
CustomerID Date Store Amount NoStub
1 6/7/2013 Nike 4000 2
2 6/7/2013 Adidas 6000 3
This table will be updating, for example I will be using table named "StubRange", This output will be generate.
RangeID CustomerID NoStub TickerStart TickerEnd
1 1 2 00001 00002
2 2 3 00003 00005
I just want to learned how to have this kind of kind of method.
What you are looking for is an After Insert trigger.
Basically you can think of it as an event that triggers after an insert takes place (hence trigger...).
Your trigger should look something like:
CREATE TRIGGER YourTriggerName --The name of your trigger
ON Ticket --The table it will be observing
AFTER INSERT,UPDATE --It will trigger after insert / update
AS
--The actions you want to do. For example:
DECLARE #CustomerId int
SET #CustomerId = (SELECT CustomerId FROM inserted) --you might want to use 'inserted' table
--Inset values
Insert into StubRange (CustomerID , NoStub)
Select Distinct ins.CustomerID, ins.NoStub
From Inserted ins
--Update existing records
UPDATE StubRange
set --Set what ever it is you want to update
WHERE CustomerId = #CustomerId
More about Inserted table - According to Microsoft:
The inserted table stores copies of the affected rows during INSERT
and UPDATE statements. During an insert or update transaction, new
rows are added to both the inserted table and the trigger table. The
rows in the inserted table are copies of the new rows in the trigger
table.
Well you need to write a insert trigger when ever you insert record in Ticket table. You can refer below syntax to create trigger. This is a Oracle syntax
CREATE OR REPLACE TRIGGER TRIGGER_INSERT_STUBRANGE
AFTER INSERT ON TICKET
FOR EACH ROW
DECLARE
raise_exception Exception;
BEGIN
--WRITE YOUR INSERT STATEMENT HERE
Exception
when raise_exception then
RAISE_APPLICATION_ERROR(-20001, sqlerrm );
END;
This will create an insert trigger on your table1 on updating table1 , table2 will b updated with CustomerID, NoStub from table 1 and rest of properties depends on your business logic
CREATE TRIGGER trig_Update_table
ON [tableName1]
FOR INSERT
AS
Begin
Insert into tableName2 (CustomerID , NoStub)
Select Distinct i.CustomerID, i.NoStub
from Inserted i
End
I have a table named emp with the following columns:
id int (autoincrement),
name varchar,
maxid int
I want to insert id, name, and maxid where maxid should be the value of autoincrement id.
Out of the two query options below, which one is best option and why?
option 1:
insert into emp (name,maxid) values ('abc',(select max(id)+1 from emp))
option 2:
string QRY = "insert into emp values('abc',0) select scope_identity()";
sqlcommand cmd= new sqlcommand(QRY, con);
datatable dt = new datatable();
con.open();
dt.load(cmd.executereader());
con.close();
int scopeid=int.parse(dt.rows[0][0].tostring());
QRY="update emp set maxid='"+scopeid+"' where id ='"+scopeid+"'";
cmd= new sqlcommand(QRY, con);
cmd.executenonquery();
easy way to do Demo is here
insert dbo.emp
select 'abc', IDENT_CURRENT('dbo.emp')
None of above are correct implementation of update.
But according to your scenario i would do two things.
First insert the names and use the auto increment to set the id and after that perform update no those records that do not have set yet the maxId.
Why do this in two stages ?
It is possible that we could have different result from MAX(id) and value of id set by incremental feature by database, so option 1 must be drop.
The query that could be used.
insert into emp (name) values ('abc')
update emp set maxid = id where maxid is null;
But from other hand and Serge observation, you should entirely drop this behavior if possible. Another alternative is to crate a trigger that kick after insert. Advantage of this is that above view or computed column is that you perform this operation only once.
I'll rather use INSERT INTO...SELECT statement,
INSERT INTO emp (name, maxid)
SELECT 'abc', COALESCE(MAX(id), 0) + 1
FROM emp
Select max(id)+1 could be different from autoincrement id so that option is not valid.
As for the second option it's still unnecessary complication. You can just insert with maxid NULL and then update to id
insert into emp (name,maxid) values ('abc',NULL)
update emp set maxid = id where maxid is null