Empty Result Set from Multi-Part Query - sql

I have a query in which I am getting different information about encounters from two different queries, a third query will be added.
For each one of those queries I create a table for the records of that query to be inserted into, and at the end I create a sort of Master Answer Table, where I want to insert all records from the different tables into it.
It is possible that a person may not have a result being returned for all queries.
I think I am messing up my join in the final part of the query as I am getting TWO results, which I know is impossible. I am using SQL-Server 2008.
Here is what I have written so far:
-- VARIABLE DECLARATION AND INITIALIZATION
SET ANSI_NULLS OFF
GO
DECLARE #SD DATETIME
DECLARE #ED DATETIME
-- THESE ARE PATIENT ADMIT DATES
SET #SD = '2013-01-01'
SET #ED = '2013-01-02'
-- #T1 ###############################################################
-- TABLE DECLARATION WHERE ALL RESULTS WILL GET DEPOSITED OF THE FIRST
-- QUERY WILL GET DEPOSITED. THIS TALBE WILL GET USED IN CONJUNCTION
-- WITH TWO OTHER TABLES IN ORDER TO COMPUTE THE FINAL
DECLARE #T1 TABLE (
ENCOUNTER_ID VARCHAR(200)
, MRN VARCHAR(200)
, [PT AGE] VARCHAR(200)
, [PT NAME] VARCHAR(500)
, [DAYS STAY] VARCHAR(200)
, [LACE DAYS SCORE] VARCHAR(100)
, [ACUTE ADMIT SCORE] VARCHAR(100)
)
--#####################################################################
-- #T1 RECORD INSERTIONS ##############################################
INSERT INTO #T1
SELECT
A.PT_NO
, A.MED_REC_NO
, A.PT_AGE
, A.PT_NAME
, A.DAYS_STAY
, A.LACE_DAYS_SCORE
, A.ACUTE_ADMIT_LACE_SCORE
--#####################################################################
-- DAYS STAY, ACUTE ADMIT AND RELATED SCORING -------------------------
FROM
(SELECT PT_NO
, Med_Rec_No
, Pt_Age
, Pt_Name
, Days_Stay
, CASE
WHEN Days_Stay < 1 THEN 0
WHEN Days_Stay = 1 THEN 1
WHEN Days_Stay = 2 THEN 2
WHEN Days_Stay = 3 THEN 3
WHEN Days_Stay BETWEEN 4 AND 6 THEN 4
WHEN Days_Stay BETWEEN 7 AND 13 THEN 5
WHEN Days_Stay >= 14 THEN 6
END AS LACE_DAYS_SCORE
, CASE
WHEN PLM_PT_ACCT_TYPE = 'I' THEN 3
END AS ACUTE_ADMIT_LACE_SCORE
FROM SMSDSS.BMH_PLM_PTACCT_V
WHERE DSCH_DATE BETWEEN #SD AND #ED
)A
--/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/--
-- #T2 ###############################################################
-- TABLE DECLARATION WHERE THE ER PORTION OF LACE SCORE FOR PATIENT
-- WILL GO.
DECLARE #T2 TABLE (
[MRN T2] VARCHAR(100)
, [PT NO] VARCHAR(20)
, [ER VISITS] VARCHAR (200)
, [ER VISITS LACE SCORE] VARCHAR(100)
)
--#####################################################################
-- #T2 RECORD INSERTIONS ##############################################
INSERT INTO #T2
SELECT B.MED_REC_NO
, B.Pt_No
, B.COUNT_MRN
, B.ER_LACE_SCORE
--#####################################################################
FROM
(
SELECT DISTINCT Med_Rec_No
, Pt_No
, COUNT(Pt_No) AS COUNT_MRN
, CASE
WHEN COUNT(MED_REC_NO) = 0 THEN 0
WHEN COUNT(MED_REC_NO) = 1 THEN 1
WHEN COUNT(MED_REC_NO) = 2 THEN 2
WHEN COUNT(MED_REC_NO) = 3 THEN 3
WHEN COUNT(MED_REC_NO) >= 4 THEN 4
END AS ER_LACE_SCORE
FROM SMSDSS.BMH_PLM_PTACCT_V
WHERE ADM_DATE >= '2013-01-01'
AND (
PLM_PT_ACCT_TYPE = 'I'
AND ADM_SOURCE NOT IN
('RA',
'RP'
)
)
OR PLM_PT_ACCT_TYPE = 'E'
GROUP BY MED_REC_NO, Pt_No
)B
--/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/--
-- FINAL TABLE DECLARATION WHERE ALL INTERMEDIATE RESULTS GET DEPOSITED
DECLARE #LT TABLE (
ENCOUNTER_ID VARCHAR(200)
, MRN VARCHAR(200)
, AGE VARCHAR(30)
, NAME VARCHAR(500)
, LACE_DAYS_SCORE VARCHAR(100)
, LACE_ACUTE_ADM VARCHAR(100)
-- , LACE_COMORBID_SCORE VARCHAR(100)
, LACE_ER_VISITS VARCHAR(100)
)
-- ####################################################################
INSERT INTO #LT
SELECT
Q1.ENCOUNTER_ID
, Q1.MRN
, Q1.[PT AGE]
, Q1.[PT NAME]
, Q1.[LACE DAYS SCORE]
, Q1.[ACUTE ADMIT SCORE]
, Q1.[ER VISITS LACE SCORE]
FROM
(
SELECT
DISTINCT T1.ENCOUNTER_ID
, T1.MRN
, T1.[PT AGE]
, T1.[PT NAME]
, T1.[LACE DAYS SCORE]
, T1.[ACUTE ADMIT SCORE]
, T2.[ER VISITS LACE SCORE]
FROM #T1 T1
JOIN #T2 T2
ON T1.ENCOUNTER_ID = T2.[PT NO]
)Q1
--#####################################################################
SELECT *
FROM #LT
I have updated the code at #T2 to join on the encounter number since any Med_rec_no can have a theoretically infinite amount of encounter numbers. The Med_rec_no therefore can show up multiple times in the original dbo table and this is not a problem. The #T2 table is trying to count how many times a Med_rec_no has been to a certain place in the last 6 months, so it is dynamic, meaning if I come in today, then how many times have I been in the last six months including today.
I have made the code adjustments based on commetns that lead me in a better direction from the two who have commented on this post.

I'm pretty sure when you do
SELECT PT_NO
, Med_Rec_No
, Pt_Age
, Pt_Name
, Days_Stay
, CASE
WHEN Days_Stay < 1 THEN 0
WHEN Days_Stay = 1 THEN 1
WHEN Days_Stay = 2 THEN 2
WHEN Days_Stay = 3 THEN 3
WHEN Days_Stay BETWEEN 4 AND 6 THEN 4
WHEN Days_Stay BETWEEN 7 AND 13 THEN 5
WHEN Days_Stay >= 14 THEN 6
END AS LACE_DAYS_SCORE
, CASE
WHEN PLM_PT_ACCT_TYPE = 'I' THEN 3
END AS ACUTE_ADMIT_LACE_SCORE
FROM SMSDSS.BMH_PLM_PTACCT_V
WHERE DSCH_DATE BETWEEN #SD AND #ED
There can be several rows with the same Med_Rec_No

Related

TSQL Inserting values based on integer results from select statement

I'm running the following query:
select
max(count) Max
from
(select
count(iStockID) Count
from
_etblInvJrBatchLines
group by
iStockID) X
As you know, the result of this is an integer; in this case, the result was 5.
Based on the above result, I need to insert generic values into another table, that looks like this:
INSERT INTO _etblInvJrBatches
(
cInvJrNumber -- IJ0001 Plus 1
, cInvJrDescription -- Inventory Journal Batch
, cInvJrReference -- IJR10001 Plus 1
, iCreateAgentID -- 1
, bClearAfterPost -- 1
, bAllowDupRef -- 1
, bAllowEditGLContra -- 0
, iNewLineDateOpt -- 0
, iNewLineRefOpt -- 0
, cNewLineRefDef -- ''
, bNewLineRefInc -- 0
, iNewLineDescOpt -- 0
, cNewLineDescDef -- ''
, bNewLineDescInc -- 0
, iNewLineProjectOpt -- 0
, iNewLineProjectDefID -- 0
, iNewLineWarehouseOpt -- 0
, iNewLineWarehouseDefID -- 0
, bJustCleared -- 0
, iTransactionCode -- 31 (select TrCodeID where TrCode = 'ADJ')
)
SELECT
'IJ000' -- Plus 1
, 'Inventory Journal Batch'
, 'IJR1000' -- Plus 1
, 1
, 1
, 1
, 0
, 0
, 0
, ''
, 0
, 0
, ''
, 0
, 0
, 0
, 0
, 0
, 0
, (select idTrCodes from TrCodes where Code = 'ADJ')
The only problem is, it only inserts this once.
How do I insert this 5 times based on the results I get from my first select statement?
In other words, if the integer result is 24, it needs to import / insert the above 24 times.
Thank you for assisting.
Attie.
Cant you just use a tally table?
declare #count int
set #count = (select
max(count) Max
from
(select
count(iStockID) Count
from
_etblInvJrBatchLines
group by
iStockID) X) --Hardcoded 10
IF OBJECT_ID('tempdb..#tally') IS NOT NULL
/*Then it exists*/
DROP TABLE #tally
SELECT TOP (#count) --equates to more than 30 years of dates
IDENTITY(INT,1,1) AS N
INTO #tally
FROM Master.dbo.SysColumns sc1,
Master.dbo.SysColumns sc2
--PRINT #count
INSERT INTO _etblInvJrBatches
(
cInvJrNumber -- IJ0001 Plus 1
, cInvJrDescription -- Inventory Journal Batch
, cInvJrReference -- IJR10001 Plus 1
, iCreateAgentID -- 1
, bClearAfterPost -- 1
, bAllowDupRef -- 1
, bAllowEditGLContra -- 0
, iNewLineDateOpt -- 0
, iNewLineRefOpt -- 0
, cNewLineRefDef -- ''
, bNewLineRefInc -- 0
, iNewLineDescOpt -- 0
, cNewLineDescDef -- ''
, bNewLineDescInc -- 0
, iNewLineProjectOpt -- 0
, iNewLineProjectDefID -- 0
, iNewLineWarehouseOpt -- 0
, iNewLineWarehouseDefID -- 0
, bJustCleared -- 0
, iTransactionCode -- 31 (select TrCodeID where TrCode = 'ADJ')
)
select N, 'IJ000' -- Plus 1
, 'Inventory Journal Batch'
, 'IJR1000' -- Plus 1
, 1
, 1
, 1
, 0
, 0
, 0
, ''
, 0
, 0
, ''
, 0
, 0
, 0
, 0
, 0
, 0 from #tally where n >0 and n <= #count
Result
There are many ways to accomplish this.
INSERT only inserts one row into the target table. Ultimately you are going to have to INSERT in a loop.
Possible solutions...
Do the looping in the database...
declare #count int = (select
max(count) Max
from
(select
count(iStockID) Count
from
_etblInvJrBatchLines
group by
iStockID) X)
declare #increment int =1
while #increment <= #count
{
-- do your insert here...
#increment = #increment +1
}
Do the looping in your client code.
Retrieve the count value from your initial query
For increment = 1 to #count
'execute SQL to do insert here...
Next increment
Or better (as #scsimon hinted at)...
For increment = 1 to #count
'build the VALUES () clauses for your insert statement...
Next
'execute your insert statement
I didn't realize that T-SQL allowed multiple VALUES clauses in an INSERT. Thank you #scsimon!
If it's me, I'm doing all of this in a client with code, not in the database. I'm old school, and I don't think that solutions like this scale well when built in the database as in my first example.
Thank you everyone for your contribution!
Special thanks to #Thomas as his advice worked the best in my environment.
I altered his script a little bit to accommodate the reference numbering:
declare #count int
set #count = (select
max(count) Max
from
(select
count(iStockID) Count
from
_etblInvJrBatchLines
group by
iStockID) X) --Hardcoded 10
IF OBJECT_ID('tempdb..#tally') IS NOT NULL
/*Then it exists*/
DROP TABLE #tally
SELECT TOP (#count) --equates to more than 30 years of dates
IDENTITY(INT,1,1) AS N
INTO #tally
FROM Master.dbo.SysColumns sc1,
Master.dbo.SysColumns sc2
--PRINT #count
INSERT INTO _etblInvJrBatches
(
cInvJrNumber -- IJ0001
, cInvJrDescription -- Inventory Journal Batch
, cInvJrReference -- IJR10001
, iCreateAgentID -- 1
, bClearAfterPost -- 1
, bAllowDupRef -- 1
, bAllowEditGLContra -- 0
, iNewLineDateOpt -- 0
, iNewLineRefOpt -- 0
, cNewLineRefDef -- ''
, bNewLineRefInc -- 0
, iNewLineDescOpt -- 0
, cNewLineDescDef -- ''
, bNewLineDescInc -- 0
, iNewLineProjectOpt -- 0
, iNewLineProjectDefID -- 0
, iNewLineWarehouseOpt -- 0
, iNewLineWarehouseDefID -- 0
, bJustCleared -- 0
, iTransactionCode -- 31 (select idTrCodes from TrCodes where Code = 'ADJ')
)
select
'IJ000' + cast(N as varchar)
, 'Inventory Journal Batch'
, 'IJR1000' + cast(N as varchar)
, 1
, 1
, 1
, 0
, 0
, 0
, ''
, 0
, 0
, ''
, 0
, 0
, 0
, 0
, 0
, 0
, (select idTrCodes from TrCodes where Code = 'ADJ')
from #tally where n >0 and n <= #count
This worked like a charm!
See results:Results

SQL - Complex Stored Procedure need to change value of 'case when' from integer to VarChar after being counted

I have a website for an NFL Pool. I'm able to display User Picks and the amount of Wins user has. As of now my CASE WHEN is using integer as win or lost. I would like to change it to be where 1 = 'Won' and 0 = 'Lost' but still count the amount of wins the user has.
Is this possible?
Thanks for any help.
My code:
DECLARE #commondata TABLE (FullName VARCHAR(30), Game_1 VARCHAR(30), Game_2 VARCHAR(30), Game_3 VARCHAR(30), Game_4 VARCHAR(30), Game_5 VARCHAR(30),
GameResults_1 INT, GameResults_2 INT, GameResults_3 INT, GameResults_4 INT, GameResults_5 INT)
INSERT INTO #commondata (FullName, Game_1, Game_2, Game_3, Game_4, Game_5,
GameResults_1, GameResults_2 , GameResults_3, GameResults_4, GameResults_5)
SELECT UserPicks.FullName, UserPicks.Game_1, UserPicks.Game_2, UserPicks.Game_3, UserPicks.Game_4, UserPicks.Game_5,
(CASE WHEN UserPicks.Game_1 = WeeklyResults.GameResults_1 THEN 1 ELSE 0 END) AS GameResult_1,
(CASE WHEN UserPicks.Game_2 = WeeklyResults.GameResults_2 THEN 1 ELSE 0 END) AS GameResult_2,
(CASE WHEN UserPicks.Game_3 = WeeklyResults.GameResults_3 THEN 1 ELSE 0 END) AS GameResult_3,
(CASE WHEN UserPicks.Game_4 = WeeklyResults.GameResults_4 THEN 1 ELSE 0 END) AS GameResult_4,
(CASE WHEN UserPicks.Game_5 = WeeklyResults.GameResults_5 THEN 1 ELSE 0 END) AS GameResult_5
FROM UserPicks
JOIN WeeklyResults ON UserPicks.Week = WeeklyResults.Week
WHERE WeeklyResults.Week = 'Week1'
-- Unpivot the table.
(SELECT FullName, Game_1, Game_2, Game_3, Game_4, Game_5, SUM(Points) As Total
FROM
(SELECT *
FROM #commondata) pvt
UNPIVOT
(Points FOR Game IN
(GameResults_1, GameResults_2, GameResults_3, GameResults_4, GameResults_5)
)AS Total
GROUP BY FullName, Game_1, Game_2, Game_3, Game_4, Game_5)
Try this, I took the liberty to reformat, remove redundant lines and use table acronyms to make it easier to read/understand:
DECLARE #commondata TABLE (FullName VARCHAR(30)
, Game_1 VARCHAR(30)
, Game_2 VARCHAR(30)
, Game_3 VARCHAR(30
, Game_4 VARCHAR(30)
, Game_5 VARCHAR(30)
, GameResults_1 VARCHAR(4)
, GameResults_2 VARCHAR(4)
, GameResults_3 VARCHAR(4)
, GameResults_4 VARCHAR(4)
, GameResults_5 VARCHAR(4));
INSERT INTO #commondata
SELECT UP.FullName
, UP.Game_1
, UP.Game_2
, UP.Game_3
, UP.Game_4
, UP.Game_5
, IIF(UP.Game_1 = WR.GameResults_1, 'Won', 'Lost') AS GameResult_1
, IIF(UP.Game_2 = WR.GameResults_2, 'Won', 'Lost') AS GameResult_2
, IIF(UP.Game_3 = WR.GameResults_3, 'Won', 'Lost') AS GameResult_3
, IIF(UP.Game_4 = WR.GameResults_4, 'Won', 'Lost') AS GameResult_4
, IIF(UP.Game_5 = WR.GameResults_5, 'Won', 'Lost') AS GameResult_5
FROM UserPicks UP
JOIN WeeklyResults WR ON UP.Week = WR.Week
WHERE WR.Week = 'Week1';
-- Unpivot the table.
SELECT FullName
, Game_1
, Game_2
, Game_3
, Game_4
, Game_5
, SUM(IIF(Result='Won', 1, 0)) As Total
FROM #commondata
UNPIVOT (
Result FOR Game IN (GameResults_1
, GameResults_2
, GameResults_3
, GameResults_4
, GameResults_5)
) AS Total
GROUP BY FullName
, Game_1
, Game_2
, Game_3
, Game_4
, Game_5;

Sub Query not working properly

I am trying to insert result of subquery inside another temporary table. SubQuery works fine when i execute that only, but not when as subquery. It throws syntax error.
Error is :Incorrect syntax near ')'. It is on first line of subquery
DECLARE #TempT TABLE
(
RowID INT IDENTITY(1, 1) ,
Date DATETIME ,
Type NVARCHAR(MAX) ,
V_No INT ,
Chq_No INT ,
Description NVARCHAR(MAX) ,
Debit MONEY ,
Credit MONEY ,
voucher_type_no INT ,
status NVARCHAR(10) ,
Clr_Date DATETIME ,
Voucher_Id INT ,
Party_Name NVARCHAR(MAX) ,
DateYYYYMMDD DATETIME
)
DECLARE #i INT= 1
INSERT INTO #TempT
SELECT *
FROM ( SELECT v.date 'Date' ,
vt.voucher_type_shortname 'Type' ,
v.voucher_no 'V_No' ,
v.cheque_no 'Chq_No' ,
a.account_name 'Description' ,
( CASE WHEN SUM(v.amount) > 0 THEN SUM(v.amount)
ELSE 0
END ) Debit ,
( CASE WHEN SUM(v.amount) < 0 THEN SUM(-v.amount)
ELSE 0
END ) Credit ,
v.voucher_type_no ,
r.status ,
r.recon_date 'Clr_Date' ,
MIN(v.voucher_id) Voucher_Id ,
'' 'Party_Name' ,
CONVERT(VARCHAR(10), r.recon_date, 126) 'Date YYYY-MM-DD'
FROM voucher v
LEFT OUTER JOIN reconcilation r ON v.voucher_id = r.voucher_id
LEFT OUTER JOIN account a ON v.other_acno = a.account_no ,
voucher_type vt
WHERE v.voucher_type_no = vt.voucher_type_no
AND v.voucher_type_no > 0
AND v.other_acno = a.account_no
AND v.acc_year = 51
AND v.account_no = 10030
AND R.recon_date <= '2015-01-12'
AND R.recon_date >= '2009-04-01'
AND V.posted IN ( 1, 2 )
GROUP BY v.voucher_no ,
v.cheque_no ,
v.date ,
vt.voucher_type_shortname ,
a.account_name ,
v.voucher_type_no ,
r.status ,
r.recon_date
)
Use a alias name after the last bracket
DECLARE #TempT TABLE
(
RowID INT IDENTITY(1, 1) ,
Date DATETIME ,
Type NVARCHAR(MAX) ,
V_No INT ,
Chq_No INT ,
Description NVARCHAR(MAX) ,
Debit MONEY ,
Credit MONEY ,
voucher_type_no INT ,
status NVARCHAR(10) ,
Clr_Date DATETIME ,
Voucher_Id INT ,
Party_Name NVARCHAR(MAX) ,
DateYYYYMMDD DATETIME
)
DECLARE #i INT= 1
INSERT INTO #TempT
SELECT *
FROM ( SELECT v.date 'Date' ,
vt.voucher_type_shortname 'Type' ,
v.voucher_no 'V_No' ,
v.cheque_no 'Chq_No' ,
a.account_name 'Description' ,
( CASE WHEN SUM(v.amount) > 0 THEN SUM(v.amount)
ELSE 0
END ) Debit ,
( CASE WHEN SUM(v.amount) < 0 THEN SUM(-v.amount)
ELSE 0
END ) Credit ,
v.voucher_type_no ,
r.status ,
r.recon_date 'Clr_Date' ,
MIN(v.voucher_id) Voucher_Id ,
'' 'Party_Name' ,
CONVERT(VARCHAR(10), r.recon_date, 126) 'Date YYYY-MM-DD'
FROM voucher v
LEFT OUTER JOIN reconcilation r ON v.voucher_id = r.voucher_id
LEFT OUTER JOIN account a ON v.other_acno = a.account_no ,
voucher_type vt
WHERE v.voucher_type_no = vt.voucher_type_no
AND v.voucher_type_no > 0
AND v.other_acno = a.account_no
AND v.acc_year = 51
AND v.account_no = 10030
AND R.recon_date <= '2015-01-12'
AND R.recon_date >= '2009-04-01'
AND V.posted IN ( 1, 2 )
GROUP BY v.voucher_no ,
v.cheque_no ,
v.date ,
vt.voucher_type_shortname ,
a.account_name ,
v.voucher_type_no ,
r.status ,
r.recon_date
) TAB

Msg 102, Level 15, State 1, Line 24 Incorrect syntax near '.'

All... based on another question I've posted here recently, I built this stored procedure, but when executed, I receive the error in the title.
As you can see, I tried to remove any aliases, but it didn't matter. Not sure how to use PRINT to see the issue on this either. Of course the isolated SELECT statement works on its own.
I can even pull results from my temp table after the error appears. So is it a problem in this script or the results? Appreciate your assistance. I also only used the WHERE statement to limit the test results.
ALTER PROC ap_vhdr_test AS
SET NOCOUNT ON
IF OBJECT_ID('temp.dbo.#ap_vend_det') is NOT NULL
DROP TABLE #ap_vend_det;
CREATE TABLE #ap_vend_det
(db_name varchar(32)
, vendor_name varchar(40)
, vendor_code varchar(12)
, voucher_no varchar(16)
, invoice_num varchar(16)
, inv_date varchar(16)
, due_date varchar(16)
, apply_date varchar(16)
, total float
, line_desc varchar(40)
, company_id smallint
, gl_num varchar(32)
, acct_site varchar(32)
, sort_code varchar(32)
, nat_gl varchar(32)
, gl_desc varchar(40)
, category nvarchar(510)
, sub_category nvarchar(510)
, po_num varchar(16)
, vendor_class varchar(8)
)
INSERT INTO #ap_vend_det
EXEC sp_MSforeachdb N'IF ''?'' NOT IN ( ''model'',''tempdb'',''master'',''msdb'')
BEGIN SELECT DISTINCT db_name = ''?''
, amaster.addr1 --as vendor_name
, amaster.vendor_code --as vendor_code
, apdet.trx_ctrl_num --as voucher_no
, aphdr.doc_ctrl_num --as invoice_num
, CONVERT(varchar(16),dateadd(dd,(aphdr.date_doc - 639906),''1/1/1753''),101) --as inv_date
, CONVERT(varchar(16),dateadd(dd,(aphdr.date_due - 639906),''1/1/1753''),101) --as due_date
, CONVERT(varchar(16),dateadd(dd,(aphdr.date_applied - 639906),''1/1/1753''),101) --as apply_date
, aphdr.amt_net --as total
, aphdr.doc_desc --as line_desc
, gldet.company_id --as company_id
, gldet.account_code --as gl_num
, gldet.seg2_code --as acct_site
, gldet.seg3_code --as sort_code
, gldet.seg1_code --as nat_gl
, gldet.description --as gl_desc
, ap_coa.group_header --as category
, ap_coa.group_label --as sub_category
, apdet.po_ctrl_num --as po_num
, apvend.vend_class_code --as vendor_class
FROM ?.dbo.amaster --amaster
JOIN ?.dbo.aphdr --aphdr --**
ON amaster.vendor_code = aphdr.vendor_code
AND amaster.pay_to_code = aphdr.pay_to_code
JOIN ?.dbo.apdet --apdet
ON aphdr.trx_ctrl_num = apdet.trx_ctrl_num
JOIN ?.dbo.gldet --gldet
ON aphdr.journal_ctrl_num = gldet.journal_ctrl_num
JOIN ?.dbo.glt --glt
ON gldet.journal_ctrl_num = glt.journal_ctrl_num
JOIN ?.dbo.apvend --apvend
ON amaster.vendor_code = apvend.vendor_code
JOIN reps.dbo.ap_coa --ap_coa
ON gldet.seg1_code = ap_coa.acct_code
WHERE aphdr.date_applied >= ''734785''
END';
SELECT * FROM #ap_vend_det;
This will fail if you have database names that have spaces or other characters in them. You need to enclose them in square brackets, e.g.
FROM [?].dbo.amaster --amaster
Not only that, because you are using 3 part names, you also need to alias the tables in the FROM clause.
FROM [?].dbo.amaster amaster
JOIN [?].dbo.aphdr aphdr --**
ON amaster.vendor_code = aphdr.vendor_code
AND amaster.pay_to_code = aphdr.pay_to_code
JOIN [?].dbo.apdet apdet
ON aphdr.trx_ctrl_num = apdet.trx_ctrl_num
JOIN [?].dbo.gldet gldet
ON aphdr.journal_ctrl_num = gldet.journal_ctrl_num
JOIN [?].dbo.glt glt
ON gldet.journal_ctrl_num = glt.journal_ctrl_num
JOIN [?].dbo.apvend apvend
ON amaster.vendor_code = apvend.vendor_code
JOIN reps.dbo.ap_coa ap_coa
ON gldet.seg1_code = ap_coa.acct_code
WHERE aphdr.date_applied >= ''734785''

i need to use string variable in the Proc in sql server database 2005

I have this procedure
CREATE Proc [dbo].Salse_Ditail
-- Add the parameters for the stored procedure here
#Report_Form varchar(1) ,
#DateFrom datetime ,
#DateTo datetime ,
#COMPANYID varchar(3),
#All varchar(1) ,
#All1 varchar(1) ,
#All2 varchar(1) ,
#All3 varchar(1) ,
#All4 varchar(1) ,
#All5 varchar(1) ,
#Sector varchar(10),
#Report_Parameter nvarchar(max)
as
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
DECLARE #STRWhere nvarchar(max)
IF #All5=0 AND #All4=0 AND #All3=0 AND #All2=0 AND #All1=0 and #All=1
set #STRWhere= N'and Sector_id = #Sector'
if #Report_Form =1 or #Report_Form =3 or #Report_Form =4
SELECT RETURNREASONCODEID, SITE,SITE_NAME,Factory_id,Factory_Name,Sector_id,sector_name,Customer_name,
Customer_id,ITEMID,ITEMNAME,SALESMANID,SALESMAN_NAME,Net_Qty,Net_Salse,Gross_Sales,Gross_Qty,
NETWEIGHT_Gross,NETWEIGHT_salse_Gross,NETWEIGHT_NET,NETWEIGHT_salse_NET,Return_Sales,Free_Good,
CollectionAmount
FROM hal_bas_new_rep
WHERE DATAAREAID =#COMPANYID AND INVOICEDATE >= #DateFrom
AND INVOICEDATE <= #DateTo and Report_Activti = #Report_Form
if #Report_Form =2
SELECT RETURNREASONCODEID , RETURNREASONDESC, SITE , SITE_NAME , Factory_id ,
Factory_Name , Sector_id , sector_name , Customer_name , Customer_id ,
ITEMID , ITEMNAME , SALESMANID , SALESMAN_NAME , Return_Sales
FROM dbo.hal_bas_new_rep
WHERE DATAAREAID =#COMPANYID AND INVOICEDATE >= #DateFrom
AND INVOICEDATE <= #DateTo and Report_Activti = #Report_Form
and RETURNREASONCODEID in
(
SELECT Val
FROM dbo.fn_String_To_Table(#Report_Parameter,',',1)
)
/*
#STRWhere // question: how can I use the variable here?
*/
end
GO
As you see I'm constructing a condition for the WHERE clause in a variable, but I don't know how to use it.
I don't think what you are doing will work. What you need to do is turn the statement that constructs the variable into an appropriate condition and add that to your WHERE clause.
SELECT RETURNREASONCODEID , RETURNREASONDESC, SITE , SITE_NAME , Factory_id ,
Factory_Name , Sector_id , sector_name , Customer_name , Customer_id ,
ITEMID , ITEMNAME , SALESMANID , SALESMAN_NAME , Return_Sales
FROM dbo.hal_bas_new_rep
WHERE DATAAREAID =#COMPANYID AND INVOICEDATE >= #DateFrom
AND INVOICEDATE <= #DateTo and Report_Activti = #Report_Form
AND RETURNREASONCODEID in
(
SELECT Val
FROM dbo.fn_String_To_Table(#Report_Parameter,',',1)
)
AND (NOT(#All5=0 AND #All4=0 AND #All3=0 AND #All2=0 AND #All1=0 AND #All=1)
OR Sector_id = #Sector)
You can build all your query in the variable and use EXECUTE to get the result.
Is orrible but work