如果否则在存储过程中不起作用

时间:2014-03-13 13:05:12

标签: sql-server c#-4.0 stored-procedures if-statement

我有两个存储过程来选择和插入值。当我从列表框中选择一个项目并单击添加按钮时,代码调用SP $ select。然后出现一个新表格,我将数据提供给文本框。当我单击保存按钮时,SP $ insert工作。但是所有数据都只能插入第一个(Base)列。当我在SP $ insert中执行所有操作(选择并插入)时,它不起作用。它有什么问题?

程序1 [SP $ select]

use env
go

create proc [SP$select](
@p2 nvarchar(20),
@debug bit = 0)
as
begin
  set nocount on

    begin try
      if @p2='User Name'
        begin
            SELECT user_name FROM env.dbo.Base 
        end 

      else if @p2='Serial Number'
        begin
            SELECT ser_num FROM env.dbo.Base 
        end
    end try

    begin catch
     IF @debug = 1
       throw;
    end catch
end
set nocount off
go

程序2 [SP $ insert]

use env
go
create proc [SP$insert](
@p1 nvarchar(100),
@id int output,
@debug bit = 0)
as
begin
  set nocount on

    begin try
      if exists(select user_name from env.dbo.Base)
        begin
            INSERT INTO envanter.dbo.Base(user_name) VALUES (@p1)
            SELECT @id = @@IDENTITY
        end

      else if exists(select ser_num from env.dbo.Base)
        begin
            INSERT INTO env.dbo.Base(ser_num) VALUES (@p1)
            SELECT @id = @@IDENTITY
        end  
    end try

    begin catch
      if @debug = 1
        throw;
    end catch
set nocount off
end
go

2 个答案:

答案 0 :(得分:0)

试试这段代码

use env
go
  create proc [SP$insert](
  @p1 nvarchar(100),
  @id int output,
  @debug bit = 0)
as
begin
   set nocount on

begin try
  if exists(select user_name from env.dbo.Base)
    begin
        INSERT INTO envanter.dbo.Base(user_name) VALUES (@p1)
        SELECT @id = @@IDENTITY
    end

  if exists(select ser_num from env.dbo.Base)
    begin
        INSERT INTO env.dbo.Base(ser_num) VALUES (@p1)
        SELECT @id = @@IDENTITY
    end  
end try

begin catch
  if @debug = 1
    throw;
end catch
set nocount off
end
go

答案 1 :(得分:0)

不确定你在这里想做什么。如果表格上至少有一行基础语句"如果存在(从env.dbo.Base中选择user_name)"无论user_name值是否为null,whill总是为TRUE,因此"否则如果"部分永远不会发生