Return a message from a stored procedure to a C # application

I have a stored procedure that adds a user and with every permission I add, I want to start creating a successful message.

My stored procedure works fine, but how do I get a success message in the message dialog in my application?

I want to display below @text in the message box in my C # application.

DECLARE @text NVARCHAR(1000)
SET @text = 'This is line 1.' + CHAR(13)+CHAR(10) + 'This is line 2.'
SELECT @text

This is my call in my C # application:

    public DataTable CreateOrDropUser(string dataBase, string procedure, SqlParameter[] parameters)
    {
       try
       {
          if (dataBase.Length > 0) { procedure = dataBase + ".." + procedure; } //Set procedure to DBNAME..ProcedureName

          SqlCommand cmd1 = new SqlCommand(procedure, con);
          cmd1.CommandType = CommandType.StoredProcedure;

          foreach (SqlParameter p in parameters)
          {
              if (p != null)
              {
                  cmd1.Parameters.Add(p);
              }
          }

          con.Open();
          DataTable dt = new DataTable();
          SqlDataAdapter da = new SqlDataAdapter(cmd1);
          da.Fill(dt);
          con.Close();

          MessageBox.Show("Success"); //This should display the @text variable in my proc

          return dt;      
     }
     catch (Exception ex)
     {
        try
        {
           if (con.State == ConnectionState.Open)
           {
              con.Close();
           }
        }
        catch
        {
           MessageBox.Show("Could not connect to database. Check settings. " + ex.Message, "Connection Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }

        MessageBox.Show(ex.Message);
        return null;
      }      
    }

My saved process, just focus on sections across all the fingerprints that the text I'm adding is:

ALTER PROCEDURE [dbo].[AdminDevUserCreate]
    @SQLLoginName varchar(50),
    @SQLLoginPass varchar(50) 
AS


DECLARE @text NVARCHAR(1000)OUTPUT  

--PRINT 'Create SQL Login'
SET @text = 'Create SQL Login ' + @SQLLoginName 
-- USE [Master]

EXEC(' USE [master] CREATE LOGIN [' + @SQLLoginName + '] WITH PASSWORD=''' + @SQLLoginPass + ''', DEFAULT_DATABASE=[TestAudit], CHECK_EXPIRATION=OFF, CHECK_POLICY=OFF')

--PRINT 'Add Server Roles'
SET @text += + CHAR(13)+CHAR(10) + 'Add Server Roles'
--Add Server roles
    EXEC master..sp_addsrvrolemember @loginame = @SQLLoginName, @rolename = N'bulkadmin'
    EXEC master..sp_addsrvrolemember @loginame = @SQLLoginName, @rolename = N'processadmin'
    EXEC master..sp_addsrvrolemember @loginame = @SQLLoginName, @rolename = N'securityadmin'   
--PRINT 'Allow SQL Agent Job Manage'
SET @text += + CHAR(13)+CHAR(10) + 'Allow SQL Agent Job Manage'
--USE [MSDB]
EXEC ('msdb..sp_addrolemember ''SQLAgentOperatorRole'', ''' + @SQLLoginName + '''')

--PRINT 'Allow Trace'
SET @text += + CHAR(13)+CHAR(10) + 'Allow Trace'
--Allow trace (SQL Profiler)
--USE [MASTER]
EXEC (' USE [MASTER] GRANT ALTER TRACE TO ' + @SQLLoginName )

--PRINT 'Prevent admin proc changes '
SET @text += + CHAR(13)+CHAR(10) + 'Prevent admin proc changes '
    EXEC ('USE [TestAudit] DENY ALTER ON [TestAudit].[dbo].[Admin] TO ' + @SQLLoginName) --Prevents changes to Admin function
--PRINT 'Prevent database trigger changes'
SET @text += + CHAR(13)+CHAR(10) + 'Prevent database trigger changes'
    EXEC ('USE [TestAudit] DENY ALTER ANY DATABASE DDL TRIGGER TO ' + @SQLLoginName) --Prevents modify of [SchemaAuditTrigger]

PRINT @text
Select @text
+5
source share
5 answers

It is best to use the output parameter.

@text nvarchar(1000) OUTPUT, @text output.

SET @text = 'This is line 1.' + CHAR(13)+CHAR(10) + 'This is line 2.'

: : , , , , . , , @name, .Value

2: -

//Add these lines
SqlParameter text = new SqlParameter("@name", SqlDbType.NVarChar);
text.Direction = ParameterDirection.Output;
cmd1.Parameters.Add(text);

con.Open();
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd1);
da.Fill(dt);
con.Close();

//Change this line
MessageBox.Show(text.Value); //This should display the @text variable in my proc

, , .

3: . #:

        using (SqlConnection connection = new SqlConnection(@"Data Source=.\SQLExpress;Initial Catalog=TestDB;Integrated Security=True"))
        {
            connection.Open();
            using (SqlCommand command = connection.CreateCommand())
            {
                command.CommandType = CommandType.StoredProcedure;
                command.CommandText = "Test";

                SqlParameter text = new SqlParameter("@Text", SqlDbType.NVarChar, 1000);
                text.Direction = ParameterDirection.Output;
                command.Parameters.Add(text);

                using (DataTable dt = new DataTable())
                {
                    using (SqlDataAdapter da = new SqlDataAdapter(command))
                    {
                        da.Fill(dt);
                    }
                }

                Trace.WriteLine(text.Value);

                connection.Close();
            }
        }

:

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE Test
    @Text Nvarchar(1000) OUTPUT
AS
BEGIN
    SET NOCOUNT ON;

    SET @Text = 'test'
END
GO

, .

4: @text ,

ALTER PROCEDURE [dbo].[AdminDevUserCreate]
    @SQLLoginName varchar(50),
    @SQLLoginPass varchar(50) 
AS

DECLARE @text NVARCHAR(1000)OUTPUT  

ALTER PROCEDURE [dbo].[AdminDevUserCreate]
    @SQLLoginName varchar(50),
    @SQLLoginPass varchar(50),
    @text NVARCHAR(1000) OUTPUT 
AS

SqlParameter

SqlParameter text = new SqlParameter("@Text", SqlDbType.NVarChar, 1000);

, , NVARCHAR(1000)

PRINT @text
Select @text

+7

MVC, . ​​ .

SqlCommand SqlConnection .

. WebForms .

+2

SqlConnection.InfoMessage. T-SQL-, RAISERROR 0-9.

 public DataTable CreateOrDropUser(string dataBase, string procedure, SqlParameter[] parameters)
    {
        SqlconnecitonStringBuilder scsb = new SqlConnectionStringBuilder (connstring);
        scsb.Database = database;
        using (SqlConnection con = new SqlConnection (scsb.ConnectionString))
        {
            StringBuilder sb = new StringBuilder ();
            con.Open ();

            SqlCommand cmd1 = new SqlCommand(procedure, con);
            cmd1.CommandType = CommandType.StoredProcedure;
            foreach (SqlParameter p in parameters)
            {
                if (p != null)
                {
                    cmd1.Parameters.Add(p);
                }
            }

            conn.InfoMessage += (args => 
            {
              sb.AppendLine (args.Message);
            });
            DataTable dt = new DataTable();
            SqlDataAdapter da = new SqlDataAdapter(cmd1);
            da.Fill(dt);
            MessageBox.Show(sb);
            return dt;      
        }
    }

T-SQL:

RAISERROR(N'This is line %d', 0,0,1);
RAISERROR(N'This is line %d', 0,0,2);
+2
MessageBox.Show(dt.Rows[0][0].Tostring());

+1
source

There is text in your dt data table. you can for example

MessageBox.Show("" + dt.Rows[0][0]);
0
source

All Articles