I'm begginer to stored procedures so i start with explanation what i'm trying to achive.
I've got excel app to fetch data from SQL server. I got 6 sql SELECT statements done in a loop with changing parameters.
I'v already managed to change one SQL into stored procedure and it's working.
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE Test
#itm nvarchar(20) = 0
AS
BEGIN
SET NOCOUNT ON;
SELECT ISNULL(SUM(T.[some_field]),0) as [Sum]
FROM [some_table] AS T, [some_other_table] AS F, [some_other_table2] AS I
WHERE T.[field] = 1 AND I.[field] = #itm AND
F.[field] = T.[field] AND F.[field] = I.[field]
END
When i got this first one to work i started to wonder if it's possible to put all 6 SELECT queries into one stored procedure?
All queries results in one field which is sum of quantities.
All queries takes at least one parameter.
At the end i'd like to recive one record with 6 fields which i can simply put in excel by Range("A1").copyfromrecordset rst
instead of creating 6 different stored procedures for each SELECT
Will it be as simple as just put one SELECT after another? And what about parameters? If parameter is same for 2 queries should it be named same in both?
You could return all 6 fields from one stored procedure. At the most basic level the way to do that would be something like:
SELECT
(
SELECT ISNULL(SUM(T.[some_field]),0) as [Sum]
FROM [some_table] AS T, [some_other_table] AS F, [some_other_table2] AS I
WHERE T.[field] = 1 AND I.[field] = #itm AND
F.[field] = T.[field] AND F.[field] = I.[field]
) Field1
,
(
-- Another query
) Field2
, etc.
Related
I have a report with a lot of datasets, and I want to make it easy for maintenance. I created a stored procedure that runs multiple select statements and accesses the data with parameters.
Sample stored procedure:
CREATE [dbo].[sp_test_report]
#inputReportPart varchar(20)
AS
BEGIN
IF (#inputReportPart = '1' OR #inputReportPart = 'debug')
BEGIN
SELECT a, b, c
FROM table1
END
IF (#inputReportPart = '2' OR #inputReportPart = 'debug')
BEGIN
SELECT q, w, e
FROM table2
END
END
But when I implement it to SSRS, the default column always use the first query even the parameter value is different.
Result:
Dataset view
Dataset1 property
Dataset2 property
I try to rebuild solution, refresh field, and delete .rdl.data but it doesn't work
Any solution other than add the column manually into dataset?
i want to make it easy for maintenance then i created stored procedure that store multiple select
That won't make anything easier. Use a different stored procedure for each dataset.
SSRS doesn't actually run your procedure to determine the dataset schema. So it will always discover the first resultset in the procedure, whether it uses FMTONLY or the newer sp_describe_first_result_set.
If you really wanted to make this work you'd have to add WITH RESULT SETS to your Dataset query which enables the client to specify the resultset metadata.
I am trying to create a Crystal Report within VS2015 but I am having issues with a stored procedure. When I run my report without a stored procedure it gets all the data required and all the groups and formulas work fine. Below is my main SQL code.
SELECT type, description, hire_status, fleet_no, location, date_starting, time_finishing, date_finishing, type, week_number, changes
FROM XXXXXX INNER JOIN XXXXXX ON fleet_no= XXXXXX.fleet_no
WHERE week_number= #weekNo
When I try and add a stored procedure to the report I only get a blank report, I lose all the data from the report. The stored procedure is as follows:
USE [xxxxxx]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER Procedure [XXXXXXX].[getCurrentLocation]
#fleet varchar(50) = NULL
AS
Begin
SELECT TOP 1 (dbo.tbl_job_planning.location)
FROM dbo.tbl_job_planning
WHERE (fleet_no = #fleet) AND (date_starting <= DATEADD(week, DATEDIFF(day, 0, GETDATE()) / 7, 5))
ORDER BY date_starting DESC
end;
I pass the parameter to this stored procedure in the record selection.
I want the stored procedure to display a location on each line of the report. When I run the report with just the stored procedure I only get 1 value returned and not a value for each item in the report which is what I need.
you are getting 1 value back because you are specifying
SELECT TOP 1 (dbo.tbl_job_planning.location). Just remove TOP 1 or set the 1 to however many results you want it limited to , but certainly not one as you specified
I have a problem when I want to select more then one value in SQL Server. I found a lot of examples with SQL Server Reporting Services but I want to use this stored procedure in a Windows form application.
I have one parameter
#emp nvarchar(50)
select * from table
where crdname = #emp
This one returns table for a single crdname, but I have a situation when I need the table with all crdname.
I have a solution using C# and 2 stored procedures, one procedure for all crdname and one procedure for a single emp, but it's a lot of code for something that I'm missing.
This depends on the scope of the requirements. Do you want it to be one or all? Do you want to be able to do multiple values? For the one or all scenario:
Have a way to pass NULL to the stored procedure then change the WHERE to WHERE (#emp is NULL OR crdname = #emp).
When the parameter is NULL, the WHERE will evaluate to true and you will get all records. When the parameter is not NULL, you will pull the single value you are looking for.
For the multiple values scenario:
Change the = to IN. You might have to create a string split function since you are passing in nvarchar for the parameter.
Use the same stored procedure, but add a condition on the parameter:
CREATE PROCEDURE dbo.YourSP #emp INT = NULL --I assumed the data type
AS
BEGIN
SELECT *
FROM YourTable
WHERE crdname = #emp
OR #emp IS NULL
END;
Then when you want all the results, then call the sp like this:
EXEC dbo.YourSP
And when you want one, then do this:
EXEC dbo.YourSP 1234
You can combine both stored procedures into one, by passing in null for #emp
select *
from table
where #emp is null or crdname = #emp
If #emp is null, then the first condition is true and all rows are returned.
I would suggest two stored procedures, because the above approach is a bit convoluted. But that's just me :)
If you find yourself writing alot of sp's for your winform app, then maybe an ORM would help - e.g. Entity framework?
for example:
here is a store procedure:
IF EXISTS (
SELECT 'x'
FROM billable_acct_payout (NOLOCK)
WHERE i_billable_acct_id = #i_billable_acct_id
)
BEGIN
SELECT 'PayoutInfo' as 'TableName'
,ba.i_billable_acct_id as 'BillableAcctId'
...
just as above,when I call this store procedure and receive the data returned in c# code like this:
DataSet ds = new Dataset();
DataAdapter da...
da.Fill(ds);
Now I know that the first 'select' in 'IF EXISTS' will not return to my dataset,but the second 'select' do.
the question is,how to know whether the 'select' in store procedure will return to dataset or not?
The easiest way is to execute the stored procedure in the Management Studio and see what's returned.
As a rule of thumb, the following (maybe incomplete) list of selects will not return anything to C#:
IF EXISTS (SELECT ...)
SELECT TOP 1 #variable = Field FROM ...
SET #variable = (SELECT TOP 1 Field FROM ...)
INSERT INTO ... SELECT ...
... WHERE Field IN (SELECT ...)
... WHERE Field = (SELECT TOP 1 ...)
DECLARE ... CURSOR FOR SELECT ...
One could say that every SELECT, the results of which are not consumed by a surrounding statement or the stored procedure itself is returned to the caller.
If you got data then the stored procedure returned data to your dataset.
But in general you should think about to change that kind of stored procedures. I just did performance tests on a mssql 2000, and I think most of the results are still valid.
For example it was way faster to let a stored procedure write its results into a table and query these result table. That would be my advise to you, change your stored procedure, add a unique key as parameter and use these parameter to find your results in your results table.
i need to execute several SQL statements inside an stored procedure, save the result into a variable for later use.
SET NOCOUNT OFF
DECLARE #P TABLE
#P = SELECT d.Periodo
from [SISACT].DEPRECIACIONES d, [SISACT].CONTROL_PERIODO c
where c.vigente = 1 AND d.Periodo = c.periodo
IF ##ROWCOUNT > 0
PRINT 'Periodo ya depreciado'
So later i can do something like this
UPDATE [SISACT].ACTIVOS_FIJOS set ultimo_periodo = #p.periodo ...
I know the #P = SELECT is wrong, i saw an example where they used another stored procedure instead of a SELECT statement, i want to know if this is possible without using a stored procedure. If so, how? I'm just going to use the query once in only one stored procedure so i see no point into putting it in another stored procedure. I'm new to T-SQL and SQL server , i'm learning on my own as well and i'm sorry if this is an stupid question.
P.S: The query in this case should return just one record. I'm using SQL SERVER 2008 Express.
Thank you for any help in advance.
I think that what you want.
SET NOCOUNT OFF
DECLARE #P as CHAR(6)
SELECT p# = d.Periodo from [SISACT].DEPRECIACIONES d, [SISACT].CONTROL_PERIODO c where c.vigente = 1 AND d.Periodo = c.periodo
IF ##ROWCOUNT > 0
PRINT 'Periodo ya depreciado'
and later you can use
UPDATE [SISACT].ACTIVOS_FIJOS set ultimo_periodo = #p