0

Hello and thanks for reading.

I have a database that contains a Unique ID and Email. When I click a button I want to get all the Emails from the Database and display in my Textbox with id Emailliste.

If it works it should list all emails in the textbox with a , between them. Like this. [email protected], [email protected]

Here is my C# code:

using (SqlConnection connection = new SqlConnection("Data Source=PCM13812;Initial Catalog=Newsletter;Integrated Security=True"))
    {
        SqlCommand cmd = new SqlCommand();

        cmd.CommandText = "GetAllEmail";
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.Connection = connection;

        connection.Open();

        string email = (string)cmd.ExecuteScalar();
        EmailListe.Text = email;

        connection.Close(); 
    }

Here is my script to create the stored procedure:

CREATE PROCEDURE [dbo].[GetAllEmail]
AS
BEGIN
SET NOCOUNT ON;

DECLARE @Email nvarchar(50)
SELECT @Email = COALESCE(@Email+ ', ', '') + Email
FROM Newsletter

END

Im not sure what Im doing wrong but i hope someone can help me

9
  • 1
    Does'nt a Function is more accurate to return data? Commented Jan 20, 2014 at 14:46
  • Im not sure, if you could give me an examble i would love it. Commented Jan 20, 2014 at 14:47
  • what problem you are facing Commented Jan 20, 2014 at 14:50
  • What is not working? Do you get an exception or is the SP result always null? Commented Jan 20, 2014 at 14:51
  • Sorry forgot to say thats the problem is, my bad. The problem is that nothing get displayed in the Textbox when i click the button. Commented Jan 20, 2014 at 14:52

2 Answers 2

1

You need to select @Email from your procedure

CREATE PROCEDURE [dbo].[GetAllEmail]
AS
BEGIN
SET NOCOUNT ON;

DECLARE @Email nvarchar(50)
SELECT @Email = COALESCE(@Email+ ', ', '') + Email
FROM Newsletter

-- You need do this
SELECT @Email
END
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks now it displays something, but it ONLY display the first 2 emails. not the 3'rd 4th and so on.
Try to increase the size of @Email variable
0

Your stored procedure (if we're talking about MS SQL) is not actually returning a result, you are missing an output SELECT. With the current procedure you are only assigning a value to @Email variable.

CREATE PROCEDURE [dbo].[GetAllEmail]
AS
BEGIN
SET NOCOUNT ON;

DECLARE @Email nvarchar(50)
SELECT @Email = COALESCE(@Email+ ', ', '') + Email
FROM Newsletter

SELECT @Email --// this is missing, so the proc will actually return a result

END

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.