How to create procedure with multiple string select query in sql? - sql

I want to create procedure with multiple string select query.I want to insert data to table variable and join that temp table with other table.
I don't want to create temp table as real tables. I want to insert data to memory temp table.
Here is my procedure,
CREATE PROCEDURE sp_TempBatch
AS
DECLARE #TempBatchSerial TABLE
(
ID int,
Name nvarchar(200),
StockType nvarchar(50),
ItemNo nvarchar(50)
)
DECLARE #TempQuery as nvarchar(MAX)='',
#VendorQuery as nvarchar(MAX)=''
BEGIN
SET #TempQuery='SELECT ID,Name,'
IF StockType = '1'
BEGIN
SET #TempQuery += ' ''Batch'' as StockType,'
END
ELSE
BEGIN
SET #TempQuery += ' ''Serial'' as StockType,'
END
SET #TempQuery += 'ItemNo INTO #TempBatchSerial
FROM Stock'
EXEC (#TempQuery)
SET #VendorQuery+=' SELECT #TempBatchSerial.* FROM #TempBatchSerial
INNER JOIN Vendor
ON #TempBatchSerial.ID = Vendor.ID
INNER JOIN Partner
ON Vendor.parentid = Partner.syskey'
EXEC (#VendorQuery)
END
When execute procedure show error message of Must declare the table variable "#TempBatchSerial"

You have to refer to #tempBatchSerial via an Alias
That's the only way #tempTables can be referred or linked to.
SELECT T.* FROM #TempBatchSerial T
INNER JOIN Vendor
ON T.ID = Vendor.ID
INNER JOIN Partner
ON Vendor.parentid = Partner.syskey
If that doesn't work you can try to put the #tempTable in the #vendorQuery text.

Related

How to pass name of temp table created in main sp to inner sp in sql?

These are sample tables
UserDetails : id,UserName,IsShow
Brand : id,BrandName
Product : id,ProductName
BrandProduct:id,brandid,productid,price
If Isshow is false, show entire price else hide second -fourth digit.(Price is 5 digits)
create procedure Sp_Details
#brandid int,
#productid int,
#IsShow bit
as
begin
select SomeColumns
into #tableForMechanism
from SomeData
if #IsShow = 0 then
begin
select SomeColumns from #tableForMechanism
end
else
begin
-- Here want to pass table name created by this sp now
-- So can check that table is exist.
-- Because Inner sp is generic.From next 20 sp,have to call
-- same sp.That's why can't give same temp table name because
-- their structure may be different
exec innerDetailsProcedure
end
end
go
create procedure innerDetailsProcedure
#tablename varchar(2000)
as
begin
if OBJECT_ID(#tablename) is NULL
begin
raiserror('Table for mechanism is not created', 16, 1)
return -1
end
else
begin
--update that table
update #tablename
set price = REPLACE(Price, (SUBSTRING(Price,2, 3*#Isshow)), 'xxx')
end
end
What is size of name of temp table created?How to fetch temp table created by this sp now for this session?
So you want to inside a proc check if a #temp table exists, based on a table name that you have in a parameter to that proc? If so, see below. You have to prefix with the database name tempdb in your check with OBJECT_ID():
CREATE PROC p #t1 sysname ,#t2 sysname AS IF OBJECT_ID('tempdb..' + #t1) IS NOT NULL PRINT '#t1 exists'
IF OBJECT_ID('tempdb..' + #t2) IS NOT NULL PRINT '#t2 exists' GO
CREATE TABLE #t(c1 int)
EXEC p #t1 = '#t', #t2 = '#doesntexist'

How to declare an array in SQL server query and how to assign value into this array from other select query

ALTER PROCEDURE [dbo].[createTimeFrameReport]
AS
--BEGIN TRAN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
--declare #currentYear varchar (4)
--declare #currentMonth varchar(3)
--declare #currentDay varchar(3)
DECLARE #applicationNo varchar(20);
TYPE ListofIDs IS VARRAY(100) OF NUMBER;
//how to assign value for below code a.APPLICATION_ID into an array
SELECT #ListofIDs =a.APPLICATION_ID from BPM_PROCESS_INSTANCE a,BPM_TASK_INSTANCE b,BPM_PROCESS c where b.PROCESS_INSTANCE_ID=a.ID and c.ID=a.TYPE_ID and a.TYPE_ID=42
AND b.ASSIGNED_ROLE IN('IDB_Reviewer','IFP_TechReviewerPermitting','IFP_ProcessManager','IFP_TechReviewerAssessment')
select #ListofIDs
In SQL there is not Array variable, however some SQL features replaces the logic of that array, it depend on how you use it, and i think what you are looking for is Temporary Tables
how to create temporary tables ? , to create temp table you need to have a hashtag sign # before the name of the temp table. see sample below (2 ways to create temp table
Using CREATE TABLE
CREATE TABLE #testTempTable
(
Column1 DataType,
Column2 DataType,
Column3 DataType,
etc...
)
Using SELECT INTO #testTempTable
SELECT Column1, Column2, Column3
INTO #testTempTable
FROM SourceTableNameHere
There is also called Variable Table in SQL , you can google it to know how to use it.
NOTE: it is best practice to drop the temporary table at the end of the script to avoid errors when the script contains temp table runs in the 2nd time.
sytanx:
DROP TABLE #testTempTable
Hope it helps.
SQL Server has not array type but you can use table variables or temp tables instead.
Also please don't use outdated comma syntax, use JOIN ON instead.
TEMP TABLE:
SELECT a.APPLICATION_ID
INTO #ListofIDs
FROM BPM_PROCESS_INSTANCE a
JOIN BPM_TASK_INSTANCE b
ON b.PROCESS_INSTANCE_ID = a.ID
JOIN BPM_PROCESS c
ON c.ID = a.TYPE_ID
WHERE a.TYPE_ID = 42
AND b.ASSIGNED_ROLE IN('IDB_Reviewer',
'IFP_TechReviewerPermitting',
'IFP_ProcessManager',
'IFP_TechReviewerAssessment');
SELECT #ListofIDs;
TABLE VARIABLE:
DECLARE #ListofIDs TABLE
(
APPLICATION_ID int
);
INSERT INTO #ListofIDs(APPLICATION_ID)
SELECT a.APPLICATION_ID
FROM BPM_PROCESS_INSTANCE a
JOIN BPM_TASK_INSTANCE b
ON b.PROCESS_INSTANCE_ID = a.ID
JOIN BPM_PROCESS c
ON c.ID = a.TYPE_ID
WHERE a.TYPE_ID = 42
AND b.ASSIGNED_ROLE IN('IDB_Reviewer',
'IFP_TechReviewerPermitting',
'IFP_ProcessManager',
'IFP_TechReviewerAssessment');
SELECT #ListofIDs;

Adding column to a resultset in stored procedure

I'm working on SP, I want to add a column to a resultset. Normally this would not be a proble, but here I'm using an Exec to fill one temp-table. To that temp-table I want to add one column.
Some prestuff that puts data in one of the temp-tables with some conditions
declare #RowCount int
set #RowCount = 1
create table #Temp_HS (row int IDENTITY (1, 1) NOT NULL, h varchar(30))
Create table #tmpS (K varchar(100),
U varchar(100), Counter int, H varchar(100))
--Puts data in one temp_table with employees
insert into #Temp_HS (h)
select Login from database.dbo.Users
where Old <> 1
and TC in ('A_1', 'A_2')
and Login not in ('Steve', 'Peter', 'Gabs')
--Declaring my counter here, it sets the MaxRow which is 19 in this case
declare #Counter int
set #Counter = (select Max(row) from #Temp_HS)
select * from #Temp_HS
-- Looping, That my RowCount must be less or Equal to Counter which is 19.
while #RowCount <= #Counter
begin
Set User which was originally from the Database Login which is declared as H in the temp table.
declare #user varchar(30)
select #user = h from #Temp_HS where row = #RowCount
Here comes the tricky part, this is the Stored procedure that inserts 3 columns into a temp
table, here I want to add one colum which in this case is h from Temp_HS to the resultset.
INSERT INTO #tmpS
EXEC Database.dbo.getListCount #user,
param,
param,
param,
'something',
param
set #RowCount = #RowCount +1
end
drop table #Temp_HS
If you need any further information just ask! :)
Basically I want to add one more column to the results of my Exec SP that inserts the result into a temp_table
INSERT INTO .. EXEC requires that the table you are inserting into already exists, e.g.
-- Given this preexisting proc
CREATE PROC dbo.getListCount #user INT, -- other params
AS
SELECT #User as Col1,
'SomeVarChar' as Col2
FROM [SomeTable];
-- In your code, create the temp table to hold the data
CREATE TABLE #tmpS
(
Col1 INT,
Col2 NVARCHAR(100),
NewColumnH VARCHAR(30) -- Add the additional column up front
-- etc.
);
This is called as
INSERT INTO #tmpS(Col1, Col2)
EXEC dbo.getListCount, #User;
If you then need to do do further processing on your temp table, do this after the PROC call:
UPDATE ts
SET NewColumnH = t.h
FROM #tmpS ts INNER JOIN #Temp_HS th on th.row = #RowCount;
Actually inner join doesnt work as desireed on temp tables that is why I used this solution. Since I already had #User in a variable I choose to do this update instead.
UPDATE ts
SET NewColumnH = #User
FROM #tmpS ts
where ts.Column is null

TSQL: Using a Table in a Variable in a Function

I'm trying to do a select from a table that will need to be in a variable. I'm working with tables that are dynamically created from an application. The table will be named CMDB_CI_XXX, where XXX will be an integer value based on a value in another table. The ultimate goal is to get the CI Name from the table.
I've tried passing the pieces that make up the table name to a function and string them together and then return the name value, but I'm not allowed to use an EXEC statement in a function.
This is what I want to execute to get the name value back:
Select [Name] from 'CMDB_CI_' + C.CI_TYPE_ID + Where CI_ID = c.CI_ID
This is the code in the SP that I'd like to use the function in to get the name value:
SELECT
CI_ID,
C.CI_TYPE_ID,
CI_CUSTOM_ID,
STATUS,
CI_TYPE_NAME,
--(Select [Name] from CMDB_CI_ + C.CI_TYPE_ID + Where CI_ID = c.CI_ID)
FROM [footprints].[dbo].[CMDB50_CI_COMMON] c
join [footprints].[dbo].[CMDB50_CI_TYPE] t
on c.CI_TYPE_ID = t.CI_TYPE_ID
where status <> 'retired'
order by CI_TYPE_NAME
I'm not sure what to do with this. Please help?
Thanks,
Jennifer
-- This part would be a SP parameter I expect
DECLARE #tableName varchar(100)
SET #tableName = 'CMDB_CI_508'
-- Main SP code
DECLARE #sqlStm VARCHAR(MAX)
SET #sqlStm = 'SELECT *
FROM '+ #tableName
EXEC (#sqlStm)
Fiddle http://sqlfiddle.com/#!3/436a7/7
First off, yes, I know it's a bad design. I didn't design it. It came with the problem tracking software that my company bought for our call center. So I gave up altogether on the approach I was going for and used a cursor to pull all the the names from the various tables into one temp table and then used said temp table to join to the original query.
ALTER Proc [dbo].[CI_CurrentItems]
As
Declare #CIType nvarchar(6)
Declare #Qry nvarchar(100)
/*
Create Table Temp_CI
( T_CI_ID int,
T_CI_Type_ID int,
T_Name nvarchar(400)
)
*/
Truncate Table Temp_CI
Declare CI_Cursor Cursor For
select distinct CI_TYPE_ID FROM [footprints].[dbo].[CMDB50_CI_COMMON]
where STATUS <> 'Retired'
Open CI_Cursor
Fetch Next from CI_Cursor into #CIType
While ##FETCH_STATUS = 0
BEGIN
Set #Qry = 'Select CI_ID, CI_Type_ID, Name from Footprints.dbo.CMDB50_CI_' + #CIType
Insert into Temp_CI Exec (#Qry)
Fetch Next from CI_Cursor into #CIType
END
Close CI_Cursor
Deallocate CI_Cursor
SELECT CI_ID,
C.CI_TYPE_ID,
CI_CUSTOM_ID,
STATUS,
CI_TYPE_NAME,
T_Name
FROM [footprints].[dbo].[CMDB50_CI_COMMON] c
JOIN [footprints].[dbo].[CMDB50_CI_TYPE] t
ON c.CI_TYPE_ID = t.CI_TYPE_ID
JOIN Temp_CI tc
ON c.CI_ID = tc.T_CI_ID
AND t.CI_TYPE_ID = tc.T_CI_TYPE_ID
WHERE STATUS <> 'retired'
ORDER BY CI_TYPE_NAME

optimizing the code

I have written this code for small database but know the database size has increased,it is showing timeout error.plz help in optimizing it
Below is the code:-
IF OBJECT_ID('Temp_expo') is not null
begin
drop table Temp_expo
end
set #query3 = 'SELECT SPCT_ID_REL_LOW,SPCT_ID_REL_HIGH,ROW_NUMBER() over (order by PDBC_PFX) as TempId
INTO Temp_expo
FROM ['+ #FCTServer +'].['+#FCTDBName+'].dbo.CMC_SPCT_SUPP_CONV
where SPCT_ID_REL_LOW <> '''' and SPCT_ID_REL_HIGH <> '''''
exec (#query3)
Select #minCount= min(TempId) from Temp_expo
Select #maxCount= max(TempId) from Temp_expo
create table #ICD9SPCT
(
ICD9Code varchar(200)
}
while #minCount<=#maxCount
begin
select #low=SPCT_ID_REL_LOW,#high=SPCT_ID_REL_HIGH
from Temp_expo
where TempId=#minCount
group by SPCT_ID_REL_LOW,SPCT_ID_REL_HIGH
set #loworder = (select ISNULL(OrderId,0) from FCT_ICD9_Diag_ORDER where ICD9=#low)
set #highorder = (select ISNULL(OrderId,0) from FCT_ICD9_Diag_ORDER where ICD9=#high)
insert into #ICD9SPCT
select ICD9 from FCT_ICD9_Diag_ORDER ordert
left join #ICD9SPCT icdorder on ordert.ICD9 = icdorder.ICD9Code
where OrderId between #loworder and #highorder and icdorder.ICD9Code is null
set #minCount = #minCount+1;
end
If this is for SQL SERVER, there are some basic tips you can try:
USE: WITH (NOLOCK) after every select you use.
i.e.
select ICD9 from FCT_ICD9_Diag_ORDER ordert WITH (NOLOCK)
left join #ICD9SPCT icdorder on ordert.ICD9 = icdorder.ICD9Code
where OrderId between #loworder and #highorder and icdorder.ICD9Code is null
You can also try to change your temp tables to variable tables, by just changing the # for an # like :
create table #ICD9SPCT
(
ICD9Code varchar(200)
}
Still, the WHILE loop you are using may be the primary cause of your problem.