Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

insert into values with where clause

I am trying to programmatically enter values into my table.

I cannot use a straight Select @variables. I have to use the keyword Values.

How can I create a where clause when using Values in the insert into.

I am trying to avoid duplicates

  DECLARE @MyID INT
  DECLARE @Phone varchar(10)
  DECLARE @MyDATE DateTime
  DECLARE @Agent as varchar(50)
  DECLARE @Charge as varchar(50)
  DECLARE @Vendor as varchar(50)

  SET @MyID = 215199999
  SET @Phone = '9999999999'
  SET @MyDATE = '2010-12-04 11:56:12.000'
  SET @Agent = 'fbrown'
  SET @Charge = 'NO'
  SET @Vendor = 'NO'

  INSERT INTO [MyDB].[dbo].[Accounts]
  (MyID,Phone,MyDate,Agent,Charge,Vendor)
  VALUES (
  @MyID
  ,@Phone
  ,@MyDATE
  ,@Agent
  ,@Charge
  ,@Vendor 
  ) WHERE MyID NOT IN (@MyID)
like image 920
Internet Engineer Avatar asked Feb 06 '12 19:02

Internet Engineer


People also ask

Can we use insert with WHERE clause?

With the help of same structure table. If we want to insert in a table whose structure is same as another table then in the following example it has been demonstrated that how we can have conditional insert i.e. how we can use WHERE clause with INSERT INTO statement.

Can we use WHERE clause in insert statement in Oracle?

The Oracle INSERT INTO SELECT statement requires the data type of the source and target tables match. If you want to copy all rows from the source table to the target table, you remove the WHERE clause. Otherwise, you can specify which rows from the source table should be copied to the target table.

How do I insert a specific value in a column in SQL?

INSERT INTO Syntax Specify both the column names and the values to be inserted: INSERT INTO table_name (column1, column2, column3, ...)

Can we use multiple VALUES in WHERE clause in SQL?

The IN operator allows you to specify multiple values in a WHERE clause. The IN operator is a shorthand for multiple OR conditions.


2 Answers

IF NOT EXISTS(SELECT 1 FROM [MyDB].[dbo].[Accounts] WHERE MyID = @MyID)
    INSERT INTO [MyDB].[dbo].[Accounts]
        (MyID, Phone, MyDate, Agent, Charge, Vendor)
        VALUES 
        (@MyID, @Phone, @MyDATE, @Agent, @Charge, @Vendor)
like image 176
Joe Stefanelli Avatar answered Nov 29 '22 12:11

Joe Stefanelli


Try using

if not exists ( select top 1 * from [MyDB].[dbo].[Accounts] Where MyID = @MyID )
INSERT INTO [MyDB].[dbo].[Accounts]
  (MyID,Phone,MyDate,Agent,Charge,Vendor)
  VALUES (
  @MyID
  ,@Phone
  ,@MyDATE
  ,@Agent
  ,@Charge
  ,@Vendor 
  )
like image 30
Siva Charan Avatar answered Nov 29 '22 12:11

Siva Charan