SQL 2008 Stored Procedure with Parameters from SQL Query - sql-server-2008

I have a stored procedure that has sever parameters that need declaring when its executed. I'm trying to establish a way of using the results of a query to assign a value to one of the parameters.
For example
EXEC #return_value = [dbo].[usp_Stored_Proc_demo]
#tableName = N'tbltesting',
#Col1 = N'c1',
#Col2 = N'c2',
#Col3 = N'c3',
#Col4 = (SELECT GETDATE()),
#Col5 = N'c5',
#Col6 = N'c6',
#Col7 = N'v7',
#Col8 = N'c8'
However this doesnt work, or anything else I have tried. Is there a way of doing it??

The options open to you really involve executing the pre-query first, assign the value to a variable and then use than in the sproc call:
SELECT #MyVar = Something
FROM dbo.Somewhere
WHERE WhatIAmLookingFor = 'AnAnswer'
EXECUTE dbo.MySproc #MyVar
You can't assign parameter values inline like you want to do based on the results of another query. You could do something using dynamic SQL I expect, but would advise against unless you have a really strong reason/need.

Related

How can I pass a returned VARCHAR from a SELECT statement in a stored procedure?

Relevant code:
SELECT `startdate`, `problem`
INTO tktCompletedDate, problem
FROM servicerequest
WHERE (requestID = tktRequestID);
CASE problem
WHEN "Screen is broken" THEN
SET tktProbSpec = 'installed replacement screen';
ELSE SET tktProbSpec = 'Ran Diagnostics';
END CASE;
Trying to complete a class assignment (big surprise) and when I run this SELECT is returns the startdate and passes it into tktCompletedDate variable no problem, but the problem field does not get passed. When I check it later it says the value is NULL.

Return data from Stored procedure and use in code behind without output or out Parameter

Is there is any other way to Get the data back in code behind from stored procedure without Out Parameter.
Example:-
Create PROCEDURE [dbo].[MaxSalary]
#Msalary money OUTPUT
AS
SET NOCOUNT ON;
SELECT #Msalary = max(salary)
FROM tblSalary ;
GO
In code behind by using SqlParameter we can get the value easily like
SqlParameter outPutParameter = new SqlParameter();
outPutParameter.ParameterName = "#Msalary";
outPutParameter.SqlDbType = System.Data.SqlDbType.Money;
outPutParameter.Direction = System.Data.ParameterDirection.Output;
cmd.Parameters.Add(outPutParameter);
double maxsal = Convert.ToDouble(outPutParameter.Value);
We can use Return as well but it will not return the data in code behind. now my question is that how we achieve the same result without using output parameter.
Hope you understand.
Thanks in advance.
Create PROCEDURE [dbo].[MaxSalary]
AS
Declare #Msalary longint=0
SET NOCOUNT ON;
SELECT #Msalary = max(salary)
FROM tblSalary ;
return #Msalary
GO
//getting return value
double maxsal = (double)mycommand.ExecuteScalar();
More details can be found here

mysql procedure how to execute a query that retrieves data within a loop then return a custom value

I don't understand how procedures work even though I search for several topic/tutorial but only found pointless examples.
In PHP my code would look like this:
function getFullPathFromID($ID)
{
$path = '';
while($result = $c->query("SELECT IDParentFolder,path FROM folders WHERE ID=$ID")->fetch())
{
$ID = $result->IDParentFolder;
$path = $result->path.'/'.$path;
}
return $path;
}
I couldn't get it working with procedures, I can't even make a query to the db:
DELIMITER #
CREATE PROCEDURE getFullPathFromID(ID INT)
BEGIN
SELECT path FROM folders WHERE ID = ID;
END
#
When I execute it with a valid value I still get "MySQL returned an empty result set (i.e. zero rows)."
So how can I execute a query that retrieves data within a loop and then return a custom value (concatenation of each step's value)?
Thanks
You have a problem in your stored procedure because the scalar id has the same name as a column in the table. So, the expression:
where id = id
does not do what you expect.
You should write this as:
DELIMITER #
CREATE PROCEDURE getFullPathFromID(v_ID INT)
BEGIN
SELECT path FROM folders f WHERE f.ID = v_ID;
END
#
However, I'm not sure this will fix the problem of no rows being selected.
I finally got it working.
BEGIN
DECLARE v_IDParentFolder INT;
DECLARE v_Name VARCHAR(255);
SET path='';
REPEAT
SELECT IDParentFolder,Name INTO v_IDParentFolder, v_Name FROM folders WHERE ID = IDFolder;
SET IDFolder = v_IDParentFolder;
SET path = CONCAT(v_Name,'/',path);
UNTIL v_IDParentFolder IS null END REPEAT;
SET path = CONCAT('/',path);
END
For the "SELECT path FROM folders" I mistook 'path' for 'name' so I couldn't get any result indeed...
For the others beginners in SQL and especially procedures, a SELECT query will not save the result but return it, in order to only save the result "INTO" has to be used as in my code and these variables have to be declared at the beginning of the procedure.
Thanks to the guy who downvoted me, he has been really helpful.
Your code is wrong, using mysqli extension you should prepare to avoid sql injection.
You should not put the query into a loop, you would loop through a recordset, but in your case you are getting a single row so it makes no sense. here 's what you should really do:
$query = 'SELECT path FROM folders WHERE ID = ?';
$stmt = $mysqli->prepare($query);
$stmt->bind_param('i', $id);
if ($stmt->execute()){
$row = $stmt->fetch_assoc();
$path = $row['path'];
}
return $path;

How to increase the user' error times? unknown whether the original value is null

Before operate Access database,in the SQL express,I can just use this statement and it works very well:
UPDATE Person
SET FErrorTimes = IsNull(FErrorTimes, 0) + 1
WHERE (FUserName = #name)
by now, it reports as error syntax
can someone help me please,and thanks very much.
Access' IsNull is different than SQL Server's IsNull. In Access, IsNull accepts only one argument, and returns True or False to indicate whether that argument evaluates as Null.
Use one of these instead.
UPDATE Person
SET FErrorTimes = Nz(FErrorTimes, 0) + 1
WHERE FUserName = #name
UPDATE Person
SET FErrorTimes = IIf(FErrorTimes Is Null, 0, FErrorTimes) + 1
WHERE FUserName = #name
Note Nz() is only available for a query run within an Access session. If you're running a query from external code which connects to the Access db, use the second example.

How to determine if a parameter value was passed to a stored procedure

I want to create a stored procedure (in SQL Server 2008 R2) that will update a record in a table based on the table's PK.
The stored proc will have, for example, four parameters:
#ID int,
#Name nvarchar(50),
#Email nvarchar(80),
#Phone nvarchar(20)
How can I determine if the caller of the stored proc passes a NULL value for one (or more) of the parameters vs. if the caller didn't pass anything for one (or more) of the parameters?
C# caller example:
Caller specifies NULL for #Phone:
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.CommandText = "EditPerson";
cmd.Parameters.AddWithValue("#ID", id);
cmd.Parameters.AddWithValue("#Name", 'Frank');
cmd.Parameters.AddWithValue("#Email", 'frank#frank.com');
cmd.Parameters.AddWithValue("#Phone", DBNull.Value);
DatabaseManager.instance.ExecuteScalarQuery(cmd);
}
Caller ignores the #Phone parameter:
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.CommandText = "EditPerson";
cmd.Parameters.AddWithValue("#ID", id);
cmd.Parameters.AddWithValue("#Name", 'Frank');
cmd.Parameters.AddWithValue("#Email", 'frank#frank.com');
DatabaseManager.instance.ExecuteScalarQuery(cmd);
}
What I'm trying to accomplish here is, if the caller explicitly specifies a NULL value for a parameter, then I will update the record with a NULL value. However, if the user explicitly ignores passing a parameter, then the UPDATE query will retain the value of the field/column that is already set for the particular record (i.e. the query will NOT update that particular column).
I suppose that I could specify default values that can be safely assumed that a caller will never use - something like this:
#ID int,
#Name nvarchar(50) = 'NameIsUndefined',
#Email nvarchar(80) = 'EmailIsUndefined',
#Phone nvarchar(20) = 'PhoneIsUndefined'
Then, in the stored proc, I can check for the undefined values - if the parameter vars are still set to the NameIsUndefined, EmailIsUndefined, and/or PhoneIsUndefined values, then I can safely assume that the caller did not explicitly define values for those params. Is this the only way to accomplish my goal?
If you declare your parameters like this (without default value), the stored proc will require all four of them and will just fail if any of them will not be passed to the EXEC statement composed by the provider.
You may declare some of the parameters optional like this:
#Phone nvarchar(20) = NULL
however, there will be no way to tell inside the sproc if it was omitted or explicitly set to NULL.
There's no way to tell the difference between NULL and NULL in SQL Server, AFAIK.
In your C# code, I would A) Pass another value, like an empty string, to indicate an empty value was passed, then process that in SQL to write NULL to the DB if the value was passed, or retain the previous value if the variable is NULL, or B) Instead of passing DBNull.Value, pass the previous value that was read from the DB.