How to use SQL output parameter in NodeJS and react apps

非 Y 不嫁゛ 提交于 2021-02-11 13:44:05

问题


I have an sql Store Procedure with output parameter.I have used this output parameter to show the message from back end to front end application. and also I have used this functionality in C# code,It works fine as per my requirement.I would like to know how to use these functionality in "NodeJS and React Apps".

Please check my below sql store procedure and C# coding which I have done.It will be very useful to all of node js and react js developer to implement this.

SQL Store Procedure with output paramater :-

Create Procedure [dbo].[SpMenuParent] (

@MenuId Int,
@Message varchar(75) output,
@MenuName nvarchar(75) 

) as 

Begin
    If (@MenuId = 0)     
    begin
        if (Select Count(*) from MenuMaster Where (MenuName = @MenuName))=0
            begin
                Insert Into MenuMaster(ModuleId, MenuName,ParentId,IconCSS)Values(1,@MenuName,0, 'fa fa-dashboard')
                Set @MenuId = Cast(@@IDENTITY As Int)
            end
        else
            Set @Message = 'Duplicate Entry Not Allowed' // This will display in front end apps

    End
    else
        Update MenuMaster Set  MenuName =@MenuName Where (MenuId = @MenuId)




End 

C# Code to get output parameter from store procedure :-

private void SaveRecord()
        {
            try
            {
                string StrMessage;
                using (DbManager Db = new DbManager())
                {
                    StrMessage = Db.SetSpCommand("SpMenuParent",
                    Db.InputOutputParameter("@Message", ""),
                    Db.InputParameter("@MenuId", IntMenuId),
                    Db.InputParameter("@MenuName", TxtName.Text)).ExecuteScalar<string>(ScalarSourceType.OutputParameter);
                    Db.Dispose();
                    Db.Close();

                    if (!StrMessage="") MessageBox.Show(StrMessage); // this line get the message from sql store procedure and show it to end user

                }
            }
            catch(Exception Ex)
            {
                MessageBox.Show(Ex.Message);
            }
        }

Node JS Code :-

app.post('/createmenu', async (req, res, next) => {
  try {

        new sql.Request(conn)
          .input('message','') 
          .input('menuid', req.body.menuid)
          .input('menuname', req.body.menuname)
          .query(SpMenuParent);
      }

      res.status(201).json({ data: 'menu created' });
    });
  } catch (error) {
    console.log(error);
    res.status(400).json({ error: error });
  }
});

来源:https://stackoverflow.com/questions/61401507/how-to-use-sql-output-parameter-in-nodejs-and-react-apps

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!