SQL Server - How to insert values into one table

Asked By Ajay Paritala on 10-Feb-12 09:53 AM
How to insert values into one table after checking the condition. If condition is true then it must insert or else it must return a error message..

From front end am password values to one table2
IN table1 :id, title, description
in table2 i have : id , table1id, title,description

So now am passing values into Table2 it must check that Table1id is existing in table 1 or not how do i check the condition ? 
Suchit shah replied to Ajay Paritala on 10-Feb-12 10:02 AM
that thing you can check it in following way

1) insert the value in table1 and then by using the return statement return that ID
2) now you can check it like below 

      select Count(*) from table2 where Id = ID ( here the ID is the return ID of inserted

3) now count is greater than 0 ( zero) means row is present and if not return any row then there is no row so based on row is present or not you can perform your operation
Ajay Paritala replied to Suchit shah on 10-Feb-12 10:07 AM
I got it


but how to set error code for this?
If condition fails it must return nothing how to do this?

declare @id int

DECLARE @condition int
DECLARE @Errorcode int

SET @Errorcode = 0

set @condition = (select id from categories where id = 55)
if @condition > 0

select * from brands;


SET @Errorcode = -1
dipa ahuja replied to Ajay Paritala on 10-Feb-12 10:32 AM
    string conn = "ConnectionString";
    SqlConnection sqlcon = new SqlConnection(conn);
    comm = new SqlCommand("INSERT INTO tb2 (s.no, name,class) SELECT s.no, name , class FROM tb1", sqlcon);

kalpana aparnathi replied to Ajay Paritala on 10-Feb-12 12:49 PM
Try this Example code for your solution:

@userData TABLE(
name varchar
(30) NOT NULL,
oldlocation varchar

INSERT @userData
SELECT name, location FROM myTable
INNER JOIN otherTable ON ...
WHERE age>30;
Web Star replied to Ajay Paritala on 11-Feb-12 01:53 AM
You just put comple stored proc with output paramter which is return error

Create proc spName
  @id int,
  @Title varchar(10),
  @desc varchar(1000),
  @ReturnVal varchar(200) out

  --here you need to check first that id exist in  table1 

  If exists(Select * from table1 where id = @id)
    --here insert in table2
      inser into table2 Values(@id, @Title, @desc)
      set @ReturnVal = 'Successfully Inserted'
          set @ReturnVal = 'Error message here'