SQL SELECT or INSERT INTO query - sql

I'm working with SQL Server 2000. I need to take the results from one column (VALIMIT) and insert them into another column (VALIMIT2012) in the same table (lending_limits).
My question is do I need to do a SELECT query first, or do I just start with an INSERT INTO query and what the proper syntax would be for the INSERT INTO query.

You can do this with an UPDATE statement:
update lending_limits
set VALIMIT2012 = VALIMIT

Neither. You don't insert columns, you insert rows, so what you want is an update:
update SomeTable
set VALIMIT2012 = VALIMIT
Note: It looks like you have one column per year, which is bad database design. If you have different data for each year, you should put that in a separate table, so that you get the year as data, not part of the column name.

UPDATE TableName SET VALIMIT2012 = VALIMIT

Related

Why is 'insert into select' statement in SQL inserting as a new row and not inserting correctly?

I have table 1.
I have another empty table 2 with the following columns.
I want to insert into table 2 by selecting from table 1 - so I write the query as:
insert into table2(employee,id,zone,url)
select employee, id, zone, concat('https://',employee,'.com/',id,'?',zone)
from table1
Now my table 2 looks like this,
Now for the authcode column, I do the following and insert it into the table2.
insert into table2(authcode)
SELECT CONVERT(VARCHAR(10),HASHBYTES('MD5', substring(URL,8,100)),2)
from table2.
But the insert happens differently like this AS AN ENTIRE NEW SET OF ROWS.
Can someone help me to insert the last column to the corresponding rows instead of it creating a new one?
What you should be doing is UPDATE the table to fill the column authcode, but you could do it all in 1 step while you are inserting the rows:
insert into table2(employee,id,zone,url, authcode)
select
employee,
id,
zone,
concat('https://',employee,'.com/',id,'?',zone),
CONVERT(VARCHAR(10),HASHBYTES('MD5', substring(concat('https://',employee,'.com/',id,'?',zone),8,100)),2)
from table1
or if you want to update:
update table2
set authcode = CONVERT(VARCHAR(10),HASHBYTES('MD5', substring(URL,8,100)),2)
where authcode is null
The result you are seeing is the intended behavior for an INSERT statement. It will always insert new rows.
If you want to modify existing rows your need to use an UPDATE statement.
You can either modify your INSERT to look like what #forpas has posted to get all this work done in one step. Another option is to modify the second INSERT to be an UPDATE like the following:
update table2
set authcode = CONVERT(VARCHAR(10),HASHBYTES('MD5', substring(URL,8,100)),2)

SQL Insert Query With Condition

I am trying to insert values into 1 column of a table when a condition is satisfied.
Note: The table already contains data for all the columns but for 1 which is empty. I would like to insert value into this 1 column depending on the WHERE clause.
I have this query:
INSERT INTO <TABLE_NAME>
(COLUMN_NAME)
(VALUE)
WHERE <CONDITION>
I am getting an exception:
Incorrect Syntax Near WHERE Keyword
I am able to do this using UPDATE:
UPDATE <TABLE_NAME>
SET <COL_NAME>
WHERE <CONDITION>
But was wondering why the INSERT query was failing. Any advise appreciated.
As I understand your problem, you already have data in one row, and one column in that row does not have value, so you want to add value in to that column.
This the scenario for Update existing row, not the insert new row. You have to use UPDATE clause when data already present and you want to modify record(s). Choose insert when You want to insert new row in table.
So in your current scenario, Update Clause is your friend with Where Clause as you want to modify subset of records not all.
UPDATE <TABLE_NAME>
SET <COL_NAME>
WHERE <CONDITION>
INSERT Clause does not have any Where Clause as per any RDBMS syntax(I think). Insert is condition less sql query, While SELECT, UPDATE, DELETE all are conditional commands, you can add Where Clause in all later ones.
In order to add a value into the one column when the rows are already populated, you will need to use the update statement.
If you need to insert a new row that has a where clause, you will need to use an insert into select statement:
INSERT INTO <table> (<columns>)
SELECT <columns>
FROM <table>
WHERE <condition>;
The SQL Insert dont accept where parameters, you could check this: SQL Insert Definition...
I do not know the whole question of what you want to do, but just using the INSERT statement is not possible, however it is possible to condition the insertion of data into a table, if this data is dependent on another table or comes from another table ... check here... SQL Insert explain in wikipedia
like this:
Copying rows from other tables
INSERT INTO phone_book2
SELECT *
FROM phone_book
WHERE name IN ('John Doe', 'Peter Doe')
or
INSERT INTO phone_book2 ( [name], [phoneNumber] )
SELECT [name], [phoneNumber]
FROM phone_book
WHERE name IN ('John Doe', 'Peter Doe')
Based on your question I have the feeling that you are trying to UPDATE a column in a table rather than insert.
Something like:
UPDATE column SET value WHERE different_column_value = some_value
I know this is kinda late, for those who still want to use the where clause in an insert query, it's kinda possible with a hack.
My understanding is that, you want to insert only if a condition is true. Let's assume you have a column in your database "surname" and you want to insert only if a surname doesn't exist from the table.
You kinda want something like INSERT INTO table_name blha blha blah WHERE surname!="this_surname".
The solution is to make that cell unique from your admin panel.
Insert statement will insert a new record. You cannot apply a where clause to the record that you are inserting.
The where clause can be used to update the row that you want.
update SET = where .
But insert will not have a where clause.
Hope this answers your question
INSERT syntax cannot have WHERE clause. The only time you will find INSERT has WHERE clause is when you are using INSERT INTO...SELECT statement.
I take it the code you included is simply a template to show how you structured your query. See the SO questions here, here and the MSDN question here.
In SQL Server (which uses Transact-SQL aka T-SQL) you need an UPDATE query for INSERT where columns already have values - by using the answer #HaveNoDisplayName gave :)
If you are executing INSERT / UPDATE from code (or if you need it regularly) I would strongly recommend using a stored procedure with parameters.
You could extend the procedure further by adding an INSERT block to the procedure using an IF-ELSE to determine whether to execute INSERT new record or UPDATE an existing, as seen in this SO answer.
Finally, take a look at SQLFiddle for a sandbox playground to test your SQL without risk to your RDMS :-)
Private case I found useful: Conditional insert which avoids duplications:
-- create a temporary table with desired values
SELECT 'Peter' FirstName, 'Pan' LastName
INTO #tmp
-- insert only if row doesn't exist
INSERT INTO Persons (FirstName, LastName)
SELECT *
FROM #tmp t
WHERE NOT EXISTS (SELECT * FROM Persons where FirstName=t.FirstName and LastName=t.LastName)
If the data need to be added for a column for an existing row then it’s UPDATE.
INSERT is creating a new row in the table.
For conditional INSERT, you can use the MERGE command.

how to insert or update if there is already a record?

My table has two columns: Amount and Date
When I am adding new values, I want to update the amount if there is already a record with that date. If there is not, I want to just insert my new values.
something like:
if exists(select * from table where date = #date)
update table set amount = #amount where date = #date
else
insert table (amount, date) select #amount, date
Assuming you have at least SQL Server 2008, you could use the MERGE keyword. This keyword was added specifically for cases like yours. You specify a MERGE clause (basically a join) and then statements telling it how to handle when it does or doesn't find a match.
There's a decent example at the bottom that shows merging between a target table and a source "table" created out of a single row of parameters. To boil it down a bit, you could use something like:
MERGE [TargetTable] AS target -- This is the table we'll be updating
USING (SELECT #Date) AS source (Date) -- These are the new values
ON (target.Date = source.Date) -- Here we define how we find a "match"
WHEN MATCHED THEN -- If the date already exists:
UPDATE SET Amount = #Amount
WHEN NOT MATCHED THEN -- If the date does not already exist:
INSERT (Date, Amount) VALUES (#Date, Amount)
Note that the nested UPDATE and INSERT clauses do not specify a table. That is because we already told SQL Server which table to perform those actions on when we defined our target table (the table specified right after the MERGE keyword).
Update: This functionality is apparently not supported by SQL Server CE, so it will not work in your specific case. I am leaving this answer here as it may help others attempting to do something similar in the full version of SQL Server. For the SQL Server CE solution, check out BJury's answer.
As an alternative to IF .. NOT EXISTS, you could assert an UPDATE, and fall back on an insert. This is usually quite a performant UPSERT pattern if data generally does exist already.
UPDATE MyTable
SET Amount = #NewAmount
WHERE Date = #Date;
IF ##ROWCOUNT = 0
INSERT INTO MyTable(Amount, Date) VALUES (#NewAmount, #Date);
If you are using nhibernate ORM, then you can use SaveOrUpdate session method.

Calculate the age and Insert it to an already column via SQL Server

I have a table in database which is already has the data, but now I added new column called Vol_Age and it has NULL value. I want that column filled by calculating Age, the data comes from Vol_Date_of_Birth column, I need a query that calculate the age and insert it to the Vol_Age column.
which we can use Insert or Update, and how we can do it?!
Please forgive me for my English.
Thanks
Keep in mind that since you added the column to the database, any values within that column will retain their value. As time goes on, you will need to keep updateding the values within the database.
Another approach would be to remove the column and make it a computed column instead. This way, the age is caculated at query time rather than from your last update.
ALTER TABLE tbname ADD Vol_Age AS DATEDIFF(YEAR, Vol_Date_Of_Birth, GETDATE())
Try using the DateDiff function:
SELECT DATEDIFF(year,GETDATE(),Vol_Age)
you can use this:
UPDATE Personal_Info SET vol_Age = (SELECT (DATEDIFF(YEAR, Vol_Date_Of_Birth,GETDATE()) + CONVERT(REAL,(DATEDIFF(month, Vol_Date_Of_Birth,GETDATE()) % 12))/12) AS AGE
FROM Personal_Info)
I got answers from different places and merged the answers to get this:
UPDATE Personal_Info SET vol_Age = (select convert(int,DATEDIFF(d, Vol_Date_of_Birth, getdate())/365.25));

How to Update a Single record despite multiple Occurances of the same ID Number?

I have a table that looks like the below table:
Every time the user loan a book a new record is inserted.
The data in this table is derived or taken from another table which has no dates.
I need to update this tables based on the records in the other table: Meaning I only need to update this table based on what changes.
Example: Lets say the user return the book Starship Troopers and the book return is indicated to Yes.
How do I update just that column?
What I have tried:
I tried using the MERGE Statement but it works only with unique rows of data, meaning you get an error if the same ID appears more than once.
I also tried using a basic UPDATE Statement and a JOIN but that's not going well.
I am asking because I have ran out of ideas.
Thanks for reading
If you need to update BooksReturn in target table based on the same column in source table
UPDATE t
SET t.booksreturn = s.booksreturn
FROM target t JOIN source s
ON t.userid = s.userid
AND t.booksloaned = s.booksloaned
Here is SQLFiddle demo
You can do this by simple Update & Insert statement.....
Two table A & B
From B you want to insert data into A if not exists other wise Update that data....
,First Insert into temp table....
SELECT *
INTO #MYTEMP
FROM B
WHERE BOOKSLOANED NOT IN (SELECT BOOKSLOANED
FROM A)
,Second Check data and insert into A.
INSERT INTO A
SELECT *
FROM #MYTEMP
And at last write one simple update statement which update all data of A. If any change then it also reflect to that data otherwise data as it is.
You can also update from #MYTEMP table.