Populate ReportViewer with a dynamic stored procedure - sql-server

I need to fill a report with a stored procedure like this one:
CREATE PROCEDURE [dbo].SelectDataToReport
#table_name varchar (25),
#period varchar (25)
AS
BEGIN
DECLARE #mySql nvarchar (MAX)
SET NOCOUNT ON;
SET #mySql = 'SELECT * FROM '+#table_name+' WHERE Period = '+#period+''
EXEC (#mySql)
END
But the report only accepts stored procedure like this one:
CREATE PROCEDURE [dbo].SelectCSAT
#Period varchar (25)
AS
BEGIN
SELECT ID, CSAT, Period
FROM CSAT
WHERE Period = #Period
END
So, I don't know if there's another way to fill the report. The thing is that the database tables and columns will be changed and when the report is generated, the user selects which table and period he wants.
I appreciate your help!

all you have to do is do (if your column counts never vary, you cannot have dynamic columns)
(i do this all the time)
print #mySQL
1) Then take that statement and put it at the top of your stored procedure.
2) comment all your dynamic code out
3) go into ssrs and creating a data set will work.
4) go back into your stored procedure and comment out your sql statement and restore your dynamic code (dont forget to put back exec(#mySql)
for code example do this
CREATE PROCEDURE [dbo].SelectDataToReport
#table_name varchar (25),
#period varchar (25)
AS
BEGIN
SELECT ID , CSAT , Period FROM CSAT WHERE Period = '.'
/*DECLARE #mySql nvarchar (MAX)
SET NOCOUNT ON;
SET #mySql = 'SELECT ID , CSAT , Period FROM '+#table_name+' WHERE Period = '+#period+''
EXEC (#mySql)*/
END

Related

SQL Select table name

A database had has 4 tables that has the same columns EG. SalesJAn, SalesFeb, SalesMarch, SalesApril.
I want to run a query in SQL server or in report builder Where i can change the table name based on a selection which one of 4 tables will be queried . Eg Filter in report builder
Like this
declare #tablename varchar(50)
set #tablename = 'test'
select * from #tablename
You can create a procedure which will do a select for a given table name. This procedure could look like this:
CREATE PROCEDURE EXECUTE_SELECT
#tbl sysname
AS
BEGIN
SET NOCOUNT ON;
DECLARE #SQL NVARCHAR(MAX);
SET #SQL = N' SELECT * FROM ' + QUOTENAME(#tbl)
EXECUTE sp_executesql #SQL
END
Then you can execute this procedure for every table name you want. Please see here an example according to your description: db<>fiddle
If this doesn't help you, please point out which exactly you still need to know. Thank you.

Stored Procedure in sql for selecting columns based on input values

I am trying to code a stored procedure in SQL that does the following
Takes 2 inputs (BatchType and "Column Name").
Searches database and gives the batchdate and the data in the column = "Column name"
Code is as give below
ALTER PROCEDURE [dbo].[chartmilldata]
-- Add the parameters for the stored procedure here
(#BatchType nvarchar (50),
#Data nvarchar(50))
AS
BEGIN
-- Insert statements for procedure here
SELECT BatchDate,#Data FROM --Database-- WHERE BatchType = #BatchType
END
I am trying to select column from the database based on operator input. But I am not getting the output. It would be great if someone can give me a direction.
You may want to build out your SELECT statement as a string then execute it using sp_executesql.
See this page for more info:
https://msdn.microsoft.com/en-us/library/ms188001.aspx
This will allow you to set your query to substitute in your column name via your variable and then execute the statement. Be sure to sanitize your inputs though!
You'd need to use dynamic SQL, HOWEVER I would not recommend this solution, I don't think there is anything I can add as to why I wouldn't recommend it that isn't explained better in Erland Sommarskog in The Curse and Blessings of Dynamic SQL.
Nonetheless, if you had to do it in a stored procedure you could use something like:
ALTER PROCEDURE [dbo].[chartmilldata]
-- Add the parameters for the stored procedure here
(#BatchType nvarchar (50),
#Data nvarchar(50))
AS
BEGIN
-- DECLARE AND SET SQL TO EXECUTE
DECLARE #SQL NVARCHAR(MAX) = N'SELECT BatchDate = NULL, ' +
QUOTENAME(#Data) + N' = NULL;';
-- CHECK COLUMN IS VALID IN THE TABLE
IF EXISTS
( SELECT 1
FROM sys.columns
WHERE name = #Data
AND object_id = OBJECT_ID('dbo.YourTable', 'U')
)
BEGIN
SET #SQL = 'SELECT BatchDate, ' + QUOTENAME(#Data) +
' FROM dbo.YourTable WHERE BatchType = #BatchType;';
END
EXECUTE sp_executesql #SQL, N'#BatchType NVARCHAR(50)', #BatchType;
END
It would probably be advisable to change your input parameter #Data to be NVARCHAR(128) (or the alias SYSNAME) though, since this is the maximum for column names.

Call Stored Procedure Repeatedly for version comparison

SSMS: 2008 R2
We are having our software system updated, which may contain an unknown number of undocumented changes to the way data is entered and stored in our database. We have asked for documentation, but only have schema compares for "physical" changes to the database, not the way the data is treated. They may change in the future, but for now we have to assume not.
In order to check that our stored procedures work as expected after the update, we would like to run a sample of procedures using a sample of parameters before and after the update to compare the actual data results. The stored procedures here all take a single Id as the parameter (they are used to make SSRS reports within the software system)
I have set some things up, but I am having problems with my approach and would welcome any suggestions about either a better way to do things, or how to fix my approach. The problem is that an error is returned whenever a called stored procedure uses a temporary table. Here is what I have done:
Made a script to get a random sample of Ids for paramaters (only one table used at the moment - that's fine).
ALTER PROC [dbo].[UpdateValidation_GET_RandomIdSample](#TestSizePercent DECIMAL(6,3))
AS
-- This table is already created and will persist both sides of the update
--CREATE TABLE Live_Companion.dbo.UpdateValidationIds
--( Id INT IDENTITY(1,1)NOT NULL PRIMARY KEY CLUSTERED
-- ,MyTableId NT NULL)
IF #TestSizePercent > 100 RAISERROR('Do you even percent, bro?',16,1)
DECLARE #SQL VARCHAR(255)
TRUNCATE TABLE UpdateValidationIds
SET #SQL =
'INSERT dbo.UpdateValidationIds(Id)
SELECT TOP ' + CONVERT(VARCHAR(10),#TestSizePercent) + ' PERCENT ID FROM Live.dbo.MyTable ORDER BY NEWID()'
EXEC (#SQL)
Made a second script to run a stored procedure for each Id in the table:
ALTER PROC [dbo].[UpdateValidation_GET_ProcedureResultsManyTimes](#Procedure_Name VARCHAR(255))
AS
--DECLARE #Procedure_Name VARCHAR(255) = 'Live_Companion.dbo.MyProc'
DECLARE #ID INT
DECLARE #GET_ID CURSOR
DECLARE #SQL VARCHAR(MAX) = ''
DECLARE #MyTableId INT
DECLARE #FirstRun BIT = 1
SET #GET_ID = CURSOR FOR
SELECT Id FROM Live_Companion.dbo.UpdateValidationIds
WHERE MyTableId IS NOT NULL
OPEN #GET_ID
FETCH NEXT FROM #GET_ID INTO #ID
WHILE ##FETCH_STATUS = 0
BEGIN
SELECT #MyTableId = MyTableId FROM Live_Companion.dbo.UpdateValidationIds
WHERE Id = #ID
IF #FirstRun = 1
BEGIN
SET #SQL = 'SELECT * INTO #ProcedureOutput FROM OPENROWSET(''SQLNCLI'',''Server=SQL1;Trusted_Connection=yes;'',''EXEC ' + #Procedure_Name + ' ' + CONVERT(VARCHAR(50),#MyTableId) + ''');'
SET #FirstRun = 0
END
ELSE
BEGIN
SET #SQL = #SQL + '
INSERT #ProcedureOutput SELECT * FROM OPENROWSET(''SQLNCLI'',''Server=SQL1;Trusted_Connection=yes;'',''EXEC ' + #Procedure_Name + ' ' + CONVERT(VARCHAR(50),#MyTableId) + ''');'
END
FETCH NEXT FROM #GET_ID INTO #ID
END
SET #SQL = #SQL + '
SELECT * FROM #ProcedureOutput
DROP TABLE #ProcedureOutput'
EXEC (#SQL)
CLOSE #GET_ID
DEALLOCATE #GET_ID
So now I should be able to execute the second procedure for various stored procedures and output the results to file over a range of Ids, then repeat using the saved (initially random) Ids again after the update and compare the results.
The trouble is, it fails when any of the called procedures use a temporary table:
EDIT:
Error Message returned:
Cannot process the object "EXEC Live_Companion.dbo.MyProc 12345". The
OLE DB provider "SQLNCLI10" for linked server "(null)" indicates that
either the object has no columns or the current user does not have
permissions on that object.
Any suggestions or ideas for how to proceed?

SQL Server Select-Into stored procedure

I am trying to write a custom stored procedure to carry out a select into operation. I want to copy a table (or some columns from a table) from one database to another. I am using SQL Server 2012
CREATE Procedure select_into
AS
Begin
#selection varchar(128),
#newtabname varchar(128)
#fromtabname varchar(128)
Select selection,
INTO table1,
FROM table2,
WHERE selection = #selection AND table1 = #newtabname AND table2 =#fromtabname;
go
EXEC select_into, Ecode, relational_db.dbo.work, dbo.Work_Data;
I get an error message indicating a syntax error near the "." in relational_db.dbo.work.
I would appreciate any help in getting this right
You have a missing comma in parameter list and wrong syntax for procedure declaration. It should be::
CREATE Procedure select_into
(
#selection varchar(128),
#newtabname varchar(128),
#fromtabname varchar(128)
)
AS
Begin
BUT, in addition your syntax for an INSERT INTO contains extra commas and you cannot perform dynamic T-SQL that way.
Can I suggest you first learn TSQL's syntax for SQL Server.
Try something like this ...
CREATE Procedure select_into
#selection NVARCHAR(128),
#newtabname NVARCHAR(128),
#fromtabname NVARCHAR(128)
AS
BEGIN
SET NOCOUNT ON;
DECLARE #sql NVARCHAR(MAX);
SET #sql = N'Select ' + QUOTENAME(#selection) +
N' INTO ' + QUOTENAME(#newtabname) +
N' FROM ' + QUOTENAME(#fromtabname)
EXECUTE sp_executesql #sql
END

Dynamic parameters for sql query with "IN" operator

I have an ASP.NET website (c#) and in the code-behind I want to use the IN operator in SQL http://www.w3schools.com/sql/sql_in.asp to get data from my database.
The syntax is:
SELECT column_name(s)
FROM table_name
WHERE column_name IN (value1,value2,...)
I use a stored procedure to get data, inside this procedure I run, in the end, the select.
My question is how to build dynamically the (value1, value2, ...) part of the query? How do I send as SqlParameter(s) the values that appear in the IN operator?
The stored procedure is defined like this:
CREATE PROCEDURE [dbo].[GetAllUsers]
#ORGANIZATION_ID int = null
AS
BEGIN
SET NOCOUNT ON;
begin
SELECT *
from USERS
where ORGANIZATION_ID = #ORGANIZATION_ID
end
END
I'd like to replace the WHERE clause with something like:
WHERE ORGANIZATION in (xxxxxxxxxxxxx)
How to do this?
Thank you.
You can use dynamic sql:
CREATE PROCEDURE [dbo].[GetAllUsers]
#ORGANIZATION_ID varchar(max) = null
AS
BEGIN
declare #sql varchar(max)
#sql = 'SELECT *
from USERS
where ORGANIZATION_ID in ('+#ORGANIZATION_ID+')'
SET NOCOUNT ON;
begin
exec(#sql)
end
END
You have to change type of #ORGANIZATION_ID to varchar and run the procedure with
one id:
exec '1'
or list of ids:
exec '1,2,3,4'

Resources