I want to add multiple select queries in stored procedure by using flag - how will I do this? - sql

ALTER PROCEDURE [dbo].[UserManagement]
#flag int
AS
BEGIN
IF #flag = 1
BEGIN
SELECT
Formatid, Formatdetail, dispformat
FROM
loy_Formatdetail with (nolock)
WHERE
isactive = '1'
AND memberstatus = 'Member'
ORDER BY
FormatDetail
END
END

Related

Stored Procedure to check the existence of email in tables

I am new to SQL stored procedures. I need to write a SQL to check a email exists in multiple tables. If a email contains in First Table it returns true and should not execute the rest. Like wise if not I need to check the second table and if i found return true. Finally if i found in last Table I need to return true and else i need to return false.
I am stuck in achieving this. I tried like this. Gives me syntax errors. Please share me a solution for this.
USE Users_UserDetials;
GO
CREATE PROCEDURE Users.GetUserPermissions
#userEmail nvarchar(50),
#areaId nvarchar(10),
#villageCode nvarchar(10)
AS
SET NOCOUNT ON;
IF EXISTS (SELECT 1 FROM Users.GlobalUsers AS GU
WHERE GU.UserEmail = #userEmail)
ELSE
IF EXISTS (SELECT 1 FROM Users.AreaSpecificUsers AS AU
WHERE AU.UserEmail = #userEmail)
ELSE
IF EXISTS (SELECT 1 FROM Users.VillageSpecificUsers AS VU
WHERE VU.UserEmail = #userEmail)
ELSE
'0'
GO
USE Users_UserDetials;
GO
CREATE PROCEDURE Users.GetUserPermissions
#userEmail nvarchar(50),
#areaId nvarchar(10),
#villageCode nvarchar(10)
AS
SET NOCOUNT ON;
IF EXISTS (SELECT 1 FROM Users.GlobalUsers AS GU
WHERE GU.UserEmail = #userEmail)
BEGIN
SELECT 1
END
ELSE
IF EXISTS (SELECT 1 FROM Users.AreaSpecificUsers AS AU
WHERE AU.UserEmail = #userEmail)
BEGIN
SELECT 1
END
ELSE
IF EXISTS (SELECT 1 FROM Users.VillageSpecificUsers AS VU
WHERE VU.UserEmail = #userEmail)
BEGIN
SELECT 1
END
ELSE
BEGIN
SELECT 0
END
END

How to write stored procedure in SQL Server

I have table like this:
CREATE TABLE [dbo].[tblSingleQuery]
(
Id Int IDENTITY(1,1),
ProdId INT,
ColorId INT,
IsFront BIT DEFAULT 0
)
I want to create a stored procedure with input parameter #ColorId which will fetch the results using a where clause ColorId <> #ColorId. But when I pass #ColorId = 0 then it should exclude records having IsFront = 1.
Currently I have created the stored procedure like this:
CREATE PROCEDURE [dbo].[proc_GetProductColorImage]
#ColorId INT
AS
BEGIN
IF #ColorId = 0
BEGIN
SELECT *
FROM [tblSingleQuery]
WHERE IsFront <> 1
END
ELSE
BEGIN
SELECT *
FROM [tblSingleQuery]
WHERE ColorId <> #ColorId
END
END
How can I manage this in a single select query?
you can try this :
SELECT *
FROM [tblSingleQuery]
WHERE
(#ColorId = 0 AND IsFront <> 1 ) OR
(#ColorId != 0 AND ColorId <> #ColorId )

Execute a Stored Procedure with parameters from a SELECT

I have an SP which needs to be executed as many times as i find rows in a temporary table (Just like insertion using a select statement)
My table #OutMessageQIDs has id column (with say 10 rows)
The SP HL7_InsertComponentLog requires 5 parameters as following
EXEC [HL7_InsertComponentLog] --#iPraID,#iComponentID,#vComponentType,'Send',id
SELECT #iPrcID,#iComponentID,#vComponentType,'Send',id
FROM #OutMessageQIDs
Can i do it without using Cursor or Loop kind of thing?
EDIT 1: a little more explanation - #OutMessageQIDs is a temporary table storing the ids of items Queued in a QueueTable (in an SP). and the SP HL7_InsertComponentLog logs the Queue-ed items. Depending upon #vComponentType, it logs different type of data.
EDIT 2: SP is as :
Create Procedure [dbo].[HL7_InsertComponentLog]
#IPracID [int],
#iComponentID [bigint],
#vComponentType varchar(50),
#vStatus varchar(200),
#iOutMessageQueueID [bigint]
AS
select* from hl7_outmessagelog
IF #vStatus != 'Success'
BEGIN
SELECT -1
END
ELSE IF #vComponentType = 'LabOrder' OR #vComponentType = 'ProcedureOrder' OR #vComponentType = 'RadiologyOrder'
BEGIN
SELECT -1
END
ELSE IF #vComponentType = 'LabResult' OR #vComponentType = 'ProcedureResult'
BEGIN
INSERT INTO OrderResult_Addendum (iOrderDetailID,IUserID,DateTime_Stamp,iType,VchComments,iOrderID,iPracID,vAction,bAcknowledge)
SELECT NULL,0,dTimeStamp,NULL,NULL,#iComponentID,#iPracID,#vStatus,0
FROM HL7_OutMessageQueue Q
WHERE Q.iOutQueueID = #iOutMessageQueueID and iPracID = #iPracID
END
ELSE IF #vComponentType = 'RadiologyResult'
BEGIN
INSERT INTO OrderResult_Addendum (iOrderDetailID,IUserID,DateTime_Stamp,iType,VchComments,iOrderID,iPracID,vAction,bAcknowledge)
SELECT iOrderDetailID,0,Q.dTimeStamp,NULL,NULL,#iComponentID,#iPracID,#vStatus ,0
FROM HL7_OutMessageQueue Q
INNER JOIN OrderResultDetails det ON Q.iComponentID = det.iOrderID
WHERE Q.iOutQueueID = #iOutMessageQueueID and Q.iPracID = #iPracID
END
ELSE IF #vComponentType = 'ClinicalNotes'
BEGIN
INSERT INTO Note_provider_encounter(iReportID,iUserID,iComponentID,dEncounterDate,vaction)
SELECT #iComponentID,0,0,dTimeStamp,#vStatus
FROM HL7_OutMessageLog Where iOutMessageLogID = #iOutMessageQueueID and iPracID = #iPracID
END
ELSE IF #vComponentType = 'PatientDemo'
BEGIN
DECLARE #IPatID int
DECLARE #IUserID int
SELECT #IPatID = iPatID,#IUserID = iUserID
FROM HL7_OutMessageQueue Q
WHERE Q.iOutQueueID = #iOutMessageQueueID and iPracID = #iPracID
EXEC [dbo].[InsertPatientLog] #IPracID,#IPatID,#vStatus,#IUserID
END
No you can't EXEC a stored procedure for each row in a table without using a loop of some kind.
What does your stored procedure do? It may be possible to extract the logic from that and perform it in a set based manner against the whole table.
e.g. Just use
INSERT INTO ComponentLog
SELECT #iPrcID,#iComponentID,#vComponentType,'Send',id
FROM #OutMessageQIDs
instead of calling the stored procedure for each row.

Optimizing the stored procedure to process 3 million records

I have designed a stored procedure usign Sql Server 2005 below to compare 3 million records in each of the Profile and Source Table, and update the Source table with records exist in another table (PROFILE_BC) which will also have about 3 million records.
I am trying to Optimize this code below. Can you suggest any other method ? I just worried that this will take more than about 6 hours to complete. Can we do the same using DTS ? And ideas how this can be done using DTS. Some suggested that there is a component called, Lookup, Fuzzy Lookup that can be used. Any ideas in optimizing the same are welcome.
USE Database
GO
/****** Object: StoredProcedure [dbo].[ProcName] Script Date: 11/13/2010 17:15:04 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[ProcName]
AS
BEGIN
SET NOCOUNT ON;
DECLARE #not_on_ebc_file_xx## char(2);
SET #not_on_ebc_file_xx## = 35;
DECLARE #voters_no varchar(18);
DECLARE #candidate_id char(10);
DECLARE #perm_disq_temp char(2);
DECLARE #voters_no_jms varchar(18);
DECLARE PROFILES_CURSOR CURSOR LOCAL FAST_FORWARD
FOR SELECT CP.CANDIDATE_ID, CP.VOTERS_NO FROM PROFILE CP INNER JOIN SOURCE SR ON
CP.CANDIDATE_ID = SR.CANDIDATE_ID
WHERE CP.CANDIDATE_ID NOT LIKE 'MA%';
OPEN PROFILES_CURSOR;
FETCH NEXT FROM PROFILES_CURSOR
INTO #candidate_id, #voters_no;
WHILE ##FETCH_STATUS = 0
BEGIN
SELECT #voters_no_jms = VOTERS_NO FROM PROFILE_BC WHERE VOTERS_NO = #voters_no;
SELECT #perm_disq_temp = PERM_DISQ FROM SOURCE WHERE CANDIDATE_ID = #candidate_id;
IF (#voters_no_jms = #voters_no) -- record exists in jms_temp table/ebc file
BEGIN
IF (#perm_disq_temp = #not_on_ebc_file_xx##)
BEGIN
UPDATE SOURCE SET PERM_DISQ = '' WHERE CANDIDATE_ID = #candidate_id;
END
END
ELSE
BEGIN
IF (#perm_disq_temp = '' OR #perm_disq_temp IS NULL)
BEGIN
UPDATE SOURCE SET PERM_DISQ = #not_on_ebc_file_xx## WHERE CANDIDATE_ID = #candidate_id;
END
END
SET #voters_no_jms = '';
FETCH NEXT FROM PROFILES_CURSOR INTO #candidate_id, #voters_no;
END
CLOSE PROFILES_CURSOR;
DEALLOCATE PROFILES_CURSOR;
END
you should always try to avoid using cursors if you have performance on mind.
Instead of using a cursor you could do this. Try to think in terms of sets when dealing with SQL. I commented out the update part of the query and added a select so that you can see the data.
BEGIN TRANSACTION
DECLARE #not_on_ebc_file_xx## char(2);
SET #not_on_ebc_file_xx## = 35;
--UPDATE SR
--SET PERM_DISQ =
-- CASE WHEN NOT PROFILE_BC.VOTERS_NO IS NULL THEN
-- CASE WHEN PERM_DISQ.PERM_DISQ = #not_on_ebc_file_xx## THEN ''
-- ELSE PERM_DISQ.PERM_DISQ
-- END
-- WHEN PERM_DISQ.PERM_DISQ = '' OR PERM_DISQ IS NULL THEN #not_on_ebc_file_xx##
-- ELSE PERM_DISQ.PERM_DISQ
-- END
SELECT CASE WHEN NOT PROFILE_BC.VOTERS_NO IS NULL THEN
CASE WHEN PERM_DISQ.PERM_DISQ = #not_on_ebc_file_xx## THEN ''
ELSE PERM_DISQ.PERM_DISQ
END
WHEN PERM_DISQ.PERM_DISQ = '' OR PERM_DISQ IS NULL THEN #not_on_ebc_file_xx##
ELSE PERM_DISQ.PERM_DISQ
END AS PERM_DISQ
FROM PROFILE CP
INNER JOIN SOURCE SR
ON CP.CANDIDATE_ID = SR.CANDID_ID
LEFT JOIN PROFILE_BC
ON CP.VOTERS_NO = PROFILE_BC.VOTERS_NO
LEFT JOIN SOURCE PERM_DISQ
ON CP.CANDIDATE_ID = PERM_DISQ.CANDIDATE_ID
WHERE CP.CANDIDATE_ID NOT LIKE 'MA%';
ROLLBACK TRANSACTION;
uncomment the update and set statement and comment out the select statement to update

SQL Server stored procedure statements using table clause

I am new to SQL Server and just joined a company where somebody had created the following stored procedure which I cannot understand.
I would like all of you to help me to understand what is going on in this procedure and what can be the alternate way of doing it.
Procedure [dbo].[SP_GetUserIncompleteCheckList]
(
#GroupID as int,
#BranchID as numeric)
As
Begin
Declare #DateStart as datetime
if #GroupID = 1
begin
set #DateStart = '08/31/2010' --'09/01/2010' 'Getdate()-30
end
else
begin
set #DateStart = Getdate()-30
end
--Select ResponseDate,isNull(Submit,'Incomplete') as Status from CheckList_Response Where BranchID=#BranchID and isNull(Submit,'y') <> 'Complete' and Month(ResponseDate) = Month(GetDate()) and Year(ResponseDate) = Year(GetDate()) order by ResponseDate
declare
#T table (ResponseDate Datetime,UserResponse int,DailyCount int,WeeklyCount int,MonthlyCount int,QuaterlyCount int,HalfYearlyCount int)
insert into #T (ResponseDate,UserResponse,DailyCount,WeeklyCount,MonthlyCount,QuaterlyCount,HalfYearlyCount)
Select ResDate,
isNull((Select UserResponse from VUserResponseBranchGroupwise Where ResponseDate=A.ResDate AND CLGroup = #GroupID and BranchID = B.BranchID),0) as UserResponse,
(Select Count(CLID) From CheckList where Frequency = 'Daily' and CLGroup=#GroupID) as DailyCount,
Case Weekly
When 1 Then (Select Count(CLID) From CheckList where Frequency = 'Weekly' and CLGroup=#GroupID) Else 0
End as WeeklyCount,
Case Monthly
When 1 Then (Select Count(CLID) From CheckList where Frequency = 'Monthly' and CLGroup=#GroupID) Else 0
End as MonthlyCount,
Case Quaterly
When 1 Then (Select Count(CLID) From CheckList where Frequency = 'Quarterly' and CLGroup=#GroupID) Else 0
End as QuaterlyCount,
Case HalfYearly
When 1 Then (Select Count(CLID) From CheckList where Frequency = 'Half Yearly' and CLGroup=#GroupID) Else 0
End as HalfYearlyCount
--isNull(Submit,'Incomplete') as Status
--,RoleStatus1,RoleStatus2,RoleStatus3,RoleStatus4,RoleStatus5 */
from dbo.CheckList_DateType A
,dbo.CheckList_Response B
Where A.ResDate=B.ResponseDate
AND B.ResponseDate > #DateStart
AND isNull(B.Submit,'Incomplete') <> 'Complete'
AND B.BranchID = #BranchID
Select ResponseDate,
case UserResponse
when 0 Then 'Incomplete'
else 'Partial'
end as Status
from #T
Where UserResponse < (DailyCount+WeeklyCount+MonthlyCount+QuaterlyCount+HalfYearlyCount)
order by ResponseDate
As far as I understand its a temporary table or something...
It's a variable of type TABLE
Same as:
DECLARE #COUNTER INT // variable of type INT
DECLARE #STR VARCHAR(5) // variable of type STRING
DECLARE #TAB TABLE(COLUMN1 INT) // variable of type TABLE
You can assign values to variables using SET statements.
Example:
SET #COUNTER = 1;
But for tables, INSERT statement will do
INSERT INTO #TAB(COLUMN1) VALUES(123)
It is a table variable.
Have a look at
Table Variables In T-SQL
DECLARE #local_variable
(Transact-SQL)