Make a normal query from a stored procedure - sql

Using VB6 and SQL Server 2000
I want to convert a stored procedure to normal query
Stored procedure:
Alter PROC [dbo].[proc_New]
#CCODE VARCHAR(100),
#EmpCode VARCHAR(100)
AS
BEGIN
DECLARE #ID VARCHAR (5)
DECLARE #Des VARCHAR(10)
DECLARE #SQL VARCHAR(1000)
DECLARE #Flag INT
SELECT #Flag=0
SELECT #SQL = 'SELECT PERSONID FROM T_PERSON WHERE '
IF #CCODE<>'All'
BEGIN
IF #Flag=1
BEGIN
SELECT #SQL = #SQL+' AND (CCODE IN ('''+#CCODE+'''))'
END
ELSE
BEGIN
SELECT #SQL = #SQL+' (CCODE IN ('''+#CCODE+'''))'
SELECT #Flag=1
END
END
IF #EMPCODE<>'All'
BEGIN
IF #Flag=1
BEGIN
SELECT #SQL = #SQL+' AND (EMPCODE IN ('''+#EMPCODE+'''))'
END
ELSE
BEGIN
SELECT #SQL = #SQL+' (EMPCODE IN ('''+#EMPCODE+'''))'
SELECT #Flag=1
END
END
IF #SQL = 'SELECT EmpCode FROM EMPMST WHERE ' SELECT #SQL = 'SELECT EmpCode FROM EMPMST'
INSERT INTO table EXEC(#SQL)
GO
Procedure Explanation...
I am passing 2 parameter values like emp_code or All and company_code or All.
In the 1st parameter (Emp_Code): if the value is "All" means then query return the all the emp_code or If the values is "001" then query return the "001" emp_code only
In the 2nd Parameter (Company_Code): if the value is "All" means then query return the all the emp_code for all the company (ex: IBM, SoftTech, etc) or If the value is "IBM" means then query return all the emp_code for that company (IBM)
Above stored procedure is working fine, but I want to convert into normal query.
Can anybody help me
Need query help

Below is the simpler query, please try with this:
SELECT PERSONID FROM T_PERSON WHERE
CCODE = (
CASE WHEN #CCODE = 'ALL' THEN CCODE
ELSE #CCODE END
)
AND
EMPCODE = (
CASE WHEN #EMPCODE = 'ALL' THEN EMPCODE
ELSE #EMPCODE
END
)

You can't directly do this in SQL outside of a stored procedure, your stored procedure has several if/else statements, no structure exists in sql queries to do this, if you want to achieve this you will need to build in sripting logic from the language accessing it with (i.e. c#/php/coldfusion/etc) and then perform the individual queries.
What Language are you calling the stored procedure from, or is this directly from the SQL server?
Edit: I have not used VB6 in a while so I don't remember how to write this in VB but you would basically be copying the logic from the stored procedure to build the query and then sending the query directly from VB not letting the stored procedure do it.
e.g.
Dim sql As String
If CCODE <> 'All'
sql = 'SELECT PERSONID FROM T_PERSON WHERE AND (CCODE IN (' & CCODE & '));'
{send the query to sql server}
End If

Related

Converting a Static SQL Query into Dynamic SQL on a Stored Procedure

I have written a Stored Procedure like this,
Alter PROCEDURE sp_bestReviewer_report
(
#StartingLetter AS VARCHAR(1),
#CountsReq AS DECIMAL(3),
#ReqRev AS INT
#RequiredColumn AS SYSNAME
)
AS
BEGIN
SELECT TOP(#ReqRev) #RequiredColumn, Count(Reviewer) AS Total FROM [reviews_not_sent] WHERE LEFT(Reviewer,1) = #StartingLetter
GROUP BY (Reviewer)
HAVING (Count(Reviewer) > #CountsReq OR Count(Reviewer) < #CountsReq)
ORDER BY
Total DESC;
END;
I am trying to pass #RequiredColumn (the required column) dynamically as a parameter to the stored procedure.
How Can I do this.
You need dynamic SQL to pass in a column name:
BEGIN
DECLARE #sql NVARCHAR(MAX);
SET #sql = '
SELECT TOP (#ReqRev) [RequiredColumn], Count(Reviewer) AS Total
FROM [reviews_not_sent]
WHERE LEFT(Reviewer, 1) = #StartingLetter
GROUP BY Reviewer
HAVING Count(Reviewer) <> #CountsReq
ORDER BY Total DESC
';
SET #sql = REPLACE(#sql, '[RequiredColumn]', QUOTENAME(#RequiredColumn));
EXEC sp_executesql #sql,
N'#ReqRev int, #StartingLetter VARCHAR(1), #CountsReq DECIMAL(3)',
#ReqRev=#ReqRev, #StartingLetter=#StartingLetter, #CountsReq=#CountsReq;
END;

Pass 'IN' list in SQL Procedure

In a SQL procedure I need to pass an 'IN' list like below example
CREATE PROCEDURE [dbo].[In_List]
( #dept float
)
AS
BEGIN
select * from My_Table
where departmentId in (#dept)
;
END
exec In_List 100 --Work fine
exec In_List 102,100 --Problem is passing in list
Can someone please help me how to pass IN list thru SQL procedure. Also I need to pass another variable which is varchar. These procedure will be used for SSRS reports.
Just in case you want to go dynamic:
CREATE PROCEDURE [dbo].[In_List]
( #dept float
)
AS
declare v_sql varchar(2000)
BEGIN
set v_sql = 'select * from My_Table where departmentId in (' + #dept + ');'
;
END
Then, in SSRS:
#dept = join(Parameters!dept.value, ",")
Or, if varchar:
#dept = join(Parameters!dept.value,"','")

SQL Server - Convert SQL to Stored Procedure

Suppose I have the following structure to a set of tables in my SQL Server (2012) DB:
StartDate: Col1: Col2: .... Coln:
And, the way the DBA set up the database (have no control over that - I only have query access), all the tables with this structure that I'd want to query have, say, names beginning with MyTbl....
So, I would like to create a query that queries ALL these tables at once to get data for a specific StartDate and I've done it using the following SQL:
declare #t table(tablename varchar(50))
declare #sql varchar(max)
set #sql = ''
insert into #t
SELECT t.name AS table_name FROM sys.tables AS t
WHERE t.name LIKE 'MyTbl%'
select #sql = #sql + 'Select ''' + tablename + ''' as Table_Name, t.* From ' + tablename +
' t where StartDate = ''2015-01-01'' +
' union ' from #t
Select #sql = substring(#sql, 1, len(#sql) - 6)
exec(#sql)
In other words:
Find all tables in my DB with names beginning with MyTbl
Query each table for any data with StartDate = '2015-01-01`
Union all those queries together to get one big dataset result
The SQL works perfectly, but I'm getting quite stuck in creating a stored procedure from this query that can take in a parameter for StartDate and I don't know enough about stored procedures to do this correctly.
How could I convert this into a stored procedure that takes a date in for StartDate (to replace the ''2015-01-01'' in the query)?
Any help / guidance would be GREATLY appreciated!!!
THANKS!!!
I noticed you were not looping through each table .. here is something I had put together
CREATE PROCEDURE get_tabledata (#date DATE)
AS
BEGIN
DECLARE #t TABLE (
id INT IDENTITY(1, 1)
,tablename VARCHAR(50)
)
DECLARE #id INT
DECLARE #tablename VARCHAR(max)
DECLARE #sql VARCHAR(max)
SET #sql = ''
INSERT INTO #t
SELECT t.NAME AS table_name
FROM sys.tables AS t
WHERE t.NAME LIKE 'MyTbl%'
SET #id = ##ROWCOUNT
IF (#id > 0)
BEGIN
WHILE (#id > 0)
BEGIN
SET #tablename = (
SELECT tablename
FROM #t
WHERE id = #id
)
SELECT #sql = #sql + 'Select ' + #tablename + ''' as Table_Name, t.* From ' + #tablename + ' t where StartDate = ' + '' + convert(VARCHAR, #date) + ''
SET #sql = #sql + ' union'
Set #id = #id -1;
END
SELECT #sql = substring(#sql, 1, len(#sql) - 6)
END
EXEC (#sql)
END
While it can be a little dense if you're not used to the styling Microsoft uses on these pages, the best place to start would be the Create Procedure documentation on MSDN
https://msdn.microsoft.com/en-us/library/ms187926.aspx
That said, creating a stored procedure is pretty straight forward. Here's a really simple procedure that takes a #startDate parameter and then just returns it back. This is just to illustrate how and where you define your parameters
create procedure dbo.MyProcedure
-- put your input parameters here
#StartDate date
as
--put the body of your procedure (i.e. everything you've written in your OP) here
select #StartDate
go
YOu'll notice however that if you run this twice in a row, you get an error, because it tries to build the same procedure again. Another thing which can come in handy is adding some code before your procedure which will basically check to see if it already exists, and if it does, alter the procedure rather than just blindly re-create it.
This is a snippet from a template I use quite often which handles all of that logic for you. The simplest way to use this is press CTRL-SHIFT-M, which brings up a dialogue to replace all those tags with values you provide.
use [<Database Name, sysname,>]
go
if not exists (select 1
from sys.procedures with(nolock)
where name = '<Procedure Name, sysname,>'
and [schema_id] = schema_id('<Schema, sysname,dbo>')
and type = 'P'
)
exec ('create procedure [<Schema, sysname,dbo>].[<Procedure Name, sysname,>]
as
select ''Procedure not defined.'' as ErrorDescription
return')
--Executed as dynamic SQL since SQL Server Management Studio considures the straight SQL code a syntax error for some reason on the create procedure statement
GO
alter procedure [<Schema, sysname,dbo>].[<Procedure Name, sysname,>]
<Parm 1 Name, sysname,include [#]> <Parm 1 Datatype, sysname,><Parm 1 Default, sql_variant,include [=] if used>,
<Parm 2 Name, sysname,include [#]> <Parm 2 Datatype, sysname,><Parm 2 Default, sql_variant,include [=] if used>
as
/*******************************************************************************************************
********************************************************************************************************/
---------------------------------------------
-- declare variables
---------------------------------------------
---------------------------------------------
-- create temp tables
---------------------------------------------
---------------------------------------------
-- set session variables
---------------------------------------------
set nocount on
---------------------------------------------
-- body of stored procedure
---------------------------------------------
return

SQL: How to make table name in stored procedure dynamic

I am pretty new to SQL Server and hope someone here can help me with this (I'm using QL Server 2008).
The following is a small procedure that works as intended.
Now I would like to use the same procedure to update multiple tables as all these tables have exactly the same column names and column formatting, the only difference is the 2nd part of the table name for which I added XXX below.
Can someone tell me how this could be made dynamic and also provide me some explanations on this ?
I cannot provide much more here as I wasn't sure about how to approach this - other than probably declaring #sql nvarchar(max) and wrapping the whole query in SET #sql = N'...' before executing it.
My stored procedure:
CREATE PROCEDURE [dbo].[Cal_UpdateTeam]
#team nvarchar(100),
#teamID int,
#notes nvarchar(1000),
#log nvarchar(100),
#admin varchar(50)
AS
BEGIN
SET NOCOUNT ON;
BEGIN
IF NOT EXISTS
(
SELECT *
FROM Cal_XXX
WHERE teamID = #teamID
)
INSERT INTO Cal_XXX
(
team,
teamID,
notes,
log,
admin
)
SELECT #team,
#teamID,
#notes,
#log,
#admin
ELSE
UPDATE Cal_XXX
SET team = #team,
teamID = #teamID,
notes = #notes,
log = #log,
admin = #admin
WHERE teamID = #teamID
END
END
Many thanks for any tips and advise on this, Mike.
you should wrap your sql query in an nvarchar and then execute that query as in the below example :
declare #sql nvarchar(max)
declare #TableName nvarchar(max)
set #TableName = 'mytable'
set #sql = 'Select * from ' + #TableName
Exec sp_executesql #sql
in SP you can use Temporary Tables fro example:
CREATE PROCEDURE SELECT_TABLE
#REQUEST_ID INT
AS
BEGIN
/*************************************
** Temporary table **
*************************************/
CREATE TABLE #SOURCE (
ID INT
, ID_PARENT INT
, NAME VARCHAR(200)
, SORT INT
..
..
)
IF #REQUEST_ID = 'YES' BEGIN
INSERT INTO #SOURCE SELECT * FROM SOURCE_A
END
ELSE BEGIN
INSERT INTO #SOURCE SELECT * FROM SOURCE_B
END
SELECT * FROM #SOURCE
.....
END
GO
in SP you can encapsulate other SPs with different table names like parameter:
CREATE PROCEDURE SELECT_FROM_TABLE_A
AS
BEGIN
SELECT * FROM SOURCE_A
END
GO
CREATE PROCEDURE SELECT_FROM_TABLE_B
AS
BEGIN
SELECT * FROM SOURCE_B
END
GO
CREATE PROCEDURE SELECT_TABLE
#REQUEST_ID INT
AS
BEGIN
/**********************************************
** Subrequest select **
**********************************************/
IF #REQUEST_ID = 'YES' BEGIN
-- Request SP fro Source A
EXEC SELECT_FROM_TABLE_A
END
ELSE
BEGIN
-- Request SP fro Source B
EXEC SELECT_FROM_TABLE_B
END
END
GO

How to select Table and Column Names from passed parameters in SQL Server?

I have two very similar tables in our database, and I need to write a stored procedure for my Visual Studio 2010 Web Application to read the data from one of these tables given a table number.
Currently, we only have two tables to select from, but I can see this growing to more as this project grows.
This is sort of what I am trying to do, but this code is not correct:
PROCEDURE [dbo].[spGetData]
#tableID int
AS
BEGIN
SET NOCOUNT ON;
declare #col1 nvarchar(50), #table nvarchar(50)
set #col1=case when #tableID=1 then 'SMRequestID' else 'WHRequestID' end
set #table=case when #tableID=1 then 'SMRequest' else 'WHRequest' end
select #col1 as 'Request', WorkOrder, PartNumber, Qty, EmployeeID
from #table
END
Basically, the ColumnName and TableName depend on the #tableID parameter that will be passed in.
How would I go about doing that?
Note: My searches are not turning up anything related, but I am a C# developer and not a database developer. I imagine this has been asked before, it is just I am not using the right keywords.
Although I think Mark is quite correct given the small number of tables and simplicity of your queries, here is a dynamic sql example that passes both the table and column names:
CREATE PROCEDURE spGetData
(
#TableName nvarchar(128),
#ColumnName nvarchar(128)
)
AS
BEGIN
SET NOCOUNT ON;
DECLARE #SQL nvarchar(4000)
SET #SQL = 'SELECT ' + #ColumnName + ', as Request, WorkOrder, PartNumber, Qty, EmployeeID FROM ' + #TableName
EXEC sp_executesql #SQL
END
You can call it as follows:
exec spGetData 'SMRequest', 'SMRequestID'
exec spGetData 'WHRequest', 'WHRequestID'
One option would be to use a conditional based upon the ID and put the code for a specific table in each section for the table.
I prefer this method to get away from the dynamic sql and allow the database server to get a fighting chance to optimize the thing for speed reasons by precompiling.
NOTE: database servers are pretty bad at string manipulation (create dynamic sql) in general.
EDIT1: EXAMPLE
FOR INSTANCE: THIS SQL
declare #mytest varchar(5)
set #mytest = 'PROCS'
IF #mytest = 'PROCS'
BEGIN /* STORED PROCS */
SELECT DISTINCT
o.name AS ObjectName_StoredProcedure
FROM sysobjects as o
WHERE o.xtype = 'P'
END
ELSE
IF #mytest = 'DEFAULT'
BEGIN
SELECT DISTINCT
o.name AS ObjectName_StoredProcedure
FROM sysobjects as o
WHERE o.xtype = 'D'
END
gives you the store procedure names or the default constraints depending on what you pass to the parameter.
EDIT2: Based on OP code:
CREATE PROCEDURE [dbo].[spGetData]
(#tableID int )
AS
BEGIN
SET NOCOUNT ON;
IF #tableID = 1
BEGIN
SELECT SMSRequestId AS 'Request',
WorkOrder, PartNumber, Qty, EmployeeID
FROM SMRequest
END
IF #tableID = 2
BEGIN
SELECT WHRequestID AS 'Request',
WorkOrder, PartNumber, Qty, EmployeeID
FROM WHRequest
END
END
Do it with dynamic SQL:
PROCEDURE [dbo].[spGetData]
#tableID int
AS
BEGIN
SET NOCOUNT ON;
declare #col1 nvarchar(50), #table nvarchar(50), #cmd nvarchar(400)
set #col1=case when #tableID=1 then 'SMRequestID' else 'WHRequestID' end
set #table=case when #tableID=1 then 'SMRequest' else 'WHRequest' end
#cmd = "select " + #col1 + " as 'Request', WorkOrder, PartNumber, Qty, EmployeeID from " + #table
EXEC(#cmd)
END