I use Microsoft SQL Server.
I rarely need it, just need to add some data to an existing database. After that I may not need anything with SQL for 6 months.DECLARE @length INT -Clear! it the type
SET @length = 3 -Clear! is the assignment.
SELECT @length AS [Length] -not clear, what is [Length]SELECT @length = 5 -Clear!
SELECT @length AS [Length] -not clear!Which variant would be for the SQL Server?
Clearly you did not try the code before posting. The "AS [Length]" is simply the column alias - sets the column name. The "AS" in SQL is a very common construct and often found in JOINs.
Remove "AS [Length]" and leave "SELECT @length". The output will show "no column name" as the column name.
DECLARE @length INT
SET @length = 3
SELECT @length
In all seriousness, how do you expect to understand any solution provided on this forum if you do not understand basic syntax?
Against my better judgement, I created a sample that illustrates a basic pattern to fetch a strongly named result set and return value from a stored procedure using ADO.NET.
Stored Procedure
IF OBJECT_ID('dbo.GetUserById', 'P') IS NOT NULL
DROP PROCEDURE dbo.GetUserById;
GO
CREATE PROCEDURE dbo.GetUserById (@id INT)
AS
SET NOCOUNT ON
SELECT [UserId], [FirstName] ,[LastName], [Email]
FROM [dbo].[User]
WHERE [UserID] = @id
RETURN 10;
GO
ADO.NET / C#
static void Main(string[] args)
{
string ConnectionString = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
List<User> results = new List<User>();
int returnValue = 0;
using (SqlConnection connection = new SqlConnection(ConnectionString))
{
SqlCommand command = new SqlCommand("dbo.GetUserById", connection);
command.CommandType = CommandType.StoredProcedure;
command.Parameters.AddWithValue("@id", 1);
command.Parameters.Add("@returnValue", SqlDbType.Int).Direction = ParameterDirection.ReturnValue;
command.Connection.Open();
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
results.Add(new User()
{
UserID = (int)reader[0],
FirstName = (string)reader[1],
LastName = (string)reader[2],
Email = (string)reader[3]
});
}
reader.Close();
returnValue = (int)command.Parameters["@returnValue"].Value;
}
foreach (var item in results)
{
Console.WriteLine($"{returnValue}\t{item.UserID}\t{item.FirstName}\t{item.LastName}\t{item.Email}");
}
}
Model
public class User
{
public int UserID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
}