-1

I have a table A with column say id and attributes in this id: 1 to 20 or any others. I want a SQL query in such a way that Query will search for the particular id into the column say 11 then perform some action otherwise insert a new row with that (11) value.

In short

Search 11 in id if found then update 11 to 12 otherwise insert 11 into id
4

4 回答 4

2

使用If...Else.

IF EXISTS (SELECT * FROM TABLE_NAME WHERE id=11)
 BEGIN
     UPDATE TABLE_NAME SET ..set column with values
 END
ELSE
 BEGIN
      INSERT INTO TABLE_NAME VALUES (values....);
 END
于 2013-06-25T10:07:45.983 回答
2
if not exists(select id from some table Where id = @someid)
begin
  insert sometable(id) Values (@id)
end
else
begin
 /* do something else */
end

把事情简单化...

于 2013-06-25T09:55:47.283 回答
0

尝试这个

if not exists(select top 1 id from some table Where id = @someid)
begin
  insert sometable(id) Values (@id)
end
else
begin
 -- do something
end
于 2013-06-25T10:10:18.027 回答
0

我不确定是否有针对您的请求的查询,但我认为您可以使用 php、asp 等通过条件命令单独执行。PHP 示例在这里:

<?php
$number = 11 ;
$query = mysql_query("select * from `table` where `id` = '".$number."'");
if ( mysql_num_rows($query) >= 1 )
   {
   echo 'Existed !';
   }
else
   {
   echo 'Not existed , making :';
   $query = mysql_query('insert into `table` values ( "11", ... )');
   }
?>
于 2013-06-25T09:38:23.713 回答