SQL Server Execute stored procedure based on condition to check if a cell value contains data or not

jvlzgdj9  于 2023-04-10  发布在  其他
关注(0)|答案(2)|浏览(120)

I have SQL table(data) and it contains 3 columns.
| Id | Firstname | Lastname |
| ------------ | ------------ | ------------ |
| 1 | | |
| 2 | Abc | Def |

I have to check the Firstname column value based on the Id column. If it doesn't contain any value I need insert values into the Firstname and Lastname columns.

I tried the code below:

Create procedure prodata
   @Id navarchar(50),
   @Firstname nvarchar(50),
   @Lastname nvarchar(50)
As
Begin
    Declare @name as nvarchar(50)
    Select @name = Firstname from data where Id = @Id

    If(@name is '')
    Begin 
        Update data set Firstname= @Firstname and Lastname=@Lastname 
        where Id=@Id
    End
End
Exec prodata '1','vijay','kumar'

It is not working. How can I do this?

ldioqlga

ldioqlga1#

Please use the below procedure. I think it will helpful for you.

Create procedure prodata
        @Id nvarchar(50),
        @Firstname nvarchar(50),
        @Lastname nvarchar(50)
    As
    Begin
        Declare @name as nvarchar(50)

        Select @name = Firstname
        from data
        where Id = @Id

        If isnull(@name,'') = ''
        Begin 
            Update data set
                Firstname = @Firstname, Lastname = @Lastname
            where Id = @Id
        End
    End
5m1hhzi4

5m1hhzi42#

Try changing this:

If(@name is '')

To this:

If (coalesce(rtrim(@name), '') = '')

相关问题