How to Optimize query for creating mutiple tables with dyanamic query using SQL ServerV2014 - while-loop
I am using SQL serverV2014.
I have two tables :
Category - 26 rows Fixed
Web - Large dataset with daily data
Schema:
/* Table-1*/
CREATE TABLE Category
(
ParentCategory VARCHAR(50) NOT NULL,
CategoryMapped VARCHAR(50) NOT NULL
);
INSERT INTO Category Values
('Infectious Disease','Infectious Disease')
,('Genetics','Genetics')
,('Recent Developments in','Other')
,('Surveys','Content')
,('Pain Management','Orthopedics')
,('Psychiatry','Psychiatry')
,('Endocrinology','Endocrinology')
,('Surgery','Surgery')
,('Nursing','Other')
,('Gastroenterology','Gastroenterology')
,('Case Studies','Other')
,('Mastery of Medicine','Other')
,('Anesthesiology','Anesthesiology')
,('Oncology','Oncology/Hematology')
,('Blogs','Content')
,('Pediatrics','Pediatrics')
,('IDSA','Other')
,('Special Reports','Other')
,('Clinical Connection','Clinical Context')
,('Opinion','Other')
,('Dermatology','Dermatology')
,('Orthopedics','Orthopedics')
,('Urology','Urology')
,('HIV/AIDS','Primary Care')
,('Endocrine Society','Endocrinology')
,('OncMadness','Other')
,('TedMed','Other')
,('ASCO','Oncology/Hematology')
,('Cardiology','Cardiology')
,('Practice Management','Primary Care')
,('Building the Patient-Centered Medical Home','Other')
,('Pulmonology','Pulmonology')
,('Rheumatology','Rheumatology')
,('Emergency Medicine','Primary Care')
,('Clinical Challenges','Clinical Context')
,('Primary Care','Primary Care')
,('Transplantation','Transplantation')
,('Sports Medicine','Primary Care')
,('Oncology/Hematology','Oncology/Hematology')
,('Washington Watch','Other')
,('Meeting Coverage','Other')
,('Podcasts','Content')
,('Hospital-Based Medicine','Primary Care')
,('American College of Rheumatology','Rheumatology')
,('AAD','Dermatology')
,('Allergy & Immunology','Allergy & Immunology')
,('Geriatrics','Primary Care')
,('Neurology','Neurology')
,('Ophthalmology','Ophthalmology')
,('Pathology','Primary Care')
,('Critical Care','Primary Care')
,('Radiology','Radiology')
,('Public Health & Policy','Other')
,('Washington-Watch','Other')
,('Nephrology','Nephrology')
,('OB/Gyn','OB/Gyn')
,('Innovations in Medicine','Other')
,('AGA','Gastroenterology')
,('Clinical Focus','Clinical Context')
,('Quizzes','Other')
;
/*Table-2 */
Create table Web(
MUID VARCHAR(10) NOT NULL,
GA_TBID VARCHAR(10) NOT NULL,
EVENTDTTM DATETIME,
ParentCategory VARCHAR(100) NOT NULL,
DashboardSpecialty VARCHAR(100) NOT NULL
);
INSERT INTO Web Values
('6480030','80387','2019-01-01 09:18:05.000','Meeting Coverage','Ophthalmology')
,('6480873','80383','2019-01-11 19:26:26.000','Infectious Disease','Primary Care')
,('6480873','80388','2019-01-15 09:37:32.000','Neurology','Primary Care')
,('6480873','80383','2019-01-11 11:40:57.000','Infectious Disease','Primary Care')
,('6480873','80388','2019-01-12 09:37:35.000','Neurology','Primary Care')
,('6480873','80383','2019-01-12 11:38:51.000','Infectious Disease','Primary Care')
,('6480873','80388','2019-01-12 09:40:38.000','Neurology','Primary Care')
,('6480873','80410','2019-01-12 23:04:14.000','Public Health & Policy','Primary Care')
,('6480873','80410','2019-01-13 23:04:14.000','Public Health & Policy','Primary Care')
,('6480873','80383','2019-01-15 19:26:26.000','Infectious Disease','Primary Care')
,('6480873','80383','2019-01-11 11:40:02.000','Infectious Disease','Primary Care')
,('6480873','80383','2019-01-01 19:27:06.000','Infectious Disease','Primary Care')
,('6480873','80410','2019-01-15 23:04:53.000','Public Health & Policy','Primary Care')
,('6481093','80315','2019-01-12 16:53:03.000','Public Health & Policy','Primary Care')
,('6481093','80315','2019-01-12 08:04:44.000','Public Health & Policy','Primary Care')
,('6481482','80387','2019-01-12 09:01:58.000','Meeting Coverage','Ophthalmology')
,('6481482','80405','2019-01-12 09:00:58.000','Meeting Coverage','Ophthalmology')
,('6481812','80396','2019-01-12 23:18:28.000','Public Health & Policy','Cardiology')
,('6482049','80419','2019-01-15 19:53:57.000','Public Health & Policy','Obstetrics and Gynecology')
,('6482078','80388','2019-01-15 11:11:56.000','Neurology','Cardiology')
,('6482174','76553','2019-01-15 16:00:12.000','Opinion','Obstetrics and Gynecology')
,('6482215','80410','2019-01-15 13:50:40.000','Public Health & Policy','Primary Care')
,('6482215','80410','2019-01-11 13:52:58.000','Public Health & Policy','Primary Care')
,('6482387','80388','2019-01-11 21:44:29.000','Neurology','Dermatology')
,('6485034','79020','2019-01-11 10:22:29.000','Public Health & Policy','Primary Care')
,('6485114','80396','2019-01-11 21:02:26.000','Public Health & Policy','Primary Care')
,('6485114','80277','2019-01-12 21:26:47.000','Clinical Challenges','Primary Care')
,('6485114','79730','2019-01-12 21:28:47.000','Nursing','Primary Care')
,('6485114','80396','2019-01-12 21:02:21.000','Public Health & Policy','Primary Care')
,('6485114','79717','2019-01-12 21:28:42.000','Public Health & Policy','Primary Care');
I want to loop my query for calculating simple aggregation of data (users/week/ for each category) for very week since 2019 to current week and this data should be moved into one single table.
My Code:
DECLARE #StartDate AS DATETIME
DECLARE #EndDate AS DATETIME
DECLARE #CurrentDate AS DATETIME
SET #StartDate = '2019-01-01'
SET #EndDate = GETDATE()
SET #CurrentDate = #StartDate
WHILE (#CurrentDate < #EndDate)
BEGIN
IF ##ROWCOUNT < 1
--print #CurrentDate
/* Actual Work after every 7-days */
IF (cast(DATEPART(DAY,#CurrentDate) as INT) % 7 = 0)
BEGIN
Declare
#Week VARCHAR(10) = cast(DATEPART(WEEK,#CurrentDate) as varchar ) ,
#Year VARCHAR(10) = cast(DATEPART(YEAR,#CurrentDate) as varchar);
Declare
#Col_value VARCHAR(10) = 'W_' + #Week + '_'+ #Year;
print( cast(#CurrentDate as varchar) + ' &&& ' + #Col_value)
---Aggregating data and inserting into Tabel
Declare #query NVARCHAR(MAX) ='
select b.CategoryMapped as Category,
IFNULL(f.Users,0) as Users, ' + #Col_value + ' as WeekName
into + ' #Col_value ' + --inserting data into table
from Category b
Left join ---second join to get 26-rows from category
(
select b.CategoryMapped as Category,
count(Distinct a.MUID) as Users
from web a
left join category b ---first join to get aggregate data from web w.r.t category
on b.ParentCategory =a.ParentCategory
where DATEPART(YEAR,a.EventDTTM) = + ' #Year ' + and YEAR(WEEK,a.EventDTTM) = + ' #Week + '
group by b.CategoryMapped
)f
on b.CategoryMapped =f.Category'
execute #query
END
SET #CurrentDate = convert(varchar(30), dateadd(day,1, #CurrentDate), 101); /*increment current date*/
END
Looking at the Code I think I am doing correct. But I am not sure of performance and the way of aggrgating this data.
May I know some better way to do this task for large data? And is their any alternate way than using while loop and #dyanamicSQL for such task ?
Related
SQL Query To Get Structured Result
Sir, below is my SQL query, followed with two images of Query Result & Required Output. As you can see on Result image that I have got this output from executing the following query. There is second image of Required Output. I would need to display the output in that format. As First Department name should be at top & below Project details correspond to that department. The same cycle should get repeated for each and every department. How should I achieve this ? SQL Code: DECLARE #ColName varchar(20)=null, #Query varchar(MAX)=null, #DepartmentName varchar(50)=null, #deptt_code varchar(4)=null, #DistrictId varchar(4)='0001', #Deptt_Id char(4)=null, #stYear varchar(4)=null, #cYear varchar(4)=null, #yr varchar(9)='2017-2018', #tno int BEGIN set #stYear = SUBSTRING(#yr,0,5); set #cYear = SUBSTRING(#yr,6,4); --CREATE DYNAMIC TABLE WITH COLs DECLARE #DepartmentTable table ( department_name varchar(50), department_code varchar(4) ); DECLARE #ProjectTable table ( project_name varchar(130), project_code varchar(15), department_code varchar(4), department_name varchar(50), district_code varchar(4), district_name varchar(30), tehsil_code varchar(6), tehsil_name varchar(30), service_code varchar(3), [service_name] varchar(30), sector_code varchar(3), sector_name varchar(30), project_start_year varchar(8), project_compl_year varchar(8), financial_year varchar(9) ); --Insert into Department Table INSERT INTO #DepartmentTable (department_code, department_name) select deptt_code,deptt_name+'('+ RTRIM(LTRIM(deptt_short))+')' as dept_name from m_Department where deptt_code in (select distinct department_code from t_Project_Details where district_id=#DistrictId and financial_year=#yr); --Insert into Project Table With Corresponding Department Name & Code insert into #ProjectTable ( department_code, project_code, project_name, department_name, district_code, district_name, tehsil_code, tehsil_name, service_code, [service_name], sector_code, sector_name, project_start_year, project_compl_year, financial_year ) SELECT pd.department_code, pd.project_Code, pd.project_name, d.deptt_name, pd.district_id, di.district_name, pd.tehsil_id, t.tehsil_name, pd.service_code, s.[service_name], pd.sector_code, se.sector_name, CONVERT(varchar,YEAR(pd.project_initiation_fin_from_yr)) + ' ' + CONVERT(varchar(3),pd.project_initiation_fin_from_yr,100) as project_start_year, CONVERT(varchar,YEAR(pd.project_initiation_fin_to_yr)) + ' ' + CONVERT(varchar(3),pd.project_initiation_fin_to_yr,100) as project_compl_year, pd.financial_year FROM t_Project_Details pd INNER JOIN m_Department d ON d.deptt_code=pd.department_code INNER JOIN m_Service s ON s.service_code = pd.service_code INNER JOIN m_Sector se ON se.sector_code=pd.sector_code INNER JOIN m_District di ON di.district_code=pd.district_id INNER JOIN m_Tehsil t ON t.tehsil_code = pd.tehsil_id WHERE district_id=#DistrictId and financial_year=#yr; --select all from Department Table; select * from #ProjectTable; END Query Result Image: https://drive.google.com/open?id=0Bxn7UXgmstmRaS1qX21kbjlwZzg Required Output Image: https://drive.google.com/open?id=0Bxn7UXgmstmRekJkUWhBcmNCbk0
Your required output is a presentation layer issue; SQL can return your results but cannot make one row contain one thing and following rows contain many different things in a different format. A SQL resultset will contain the same number of columns in all rows each with the same datatype. Use something like SSRS to acheive your desire output.
SQL Server 2012 error: each GROUP BY expression must contain at least one column that is not an outer reference
My code is like this SET ANSI_NULLS OFF GO SET QUOTED_IDENTIFIER OFF GO ALTER PROCEDURE [dbo].[getprocbyproc] #flg varchar(2), #qaaprvdt char(8), #dbo varchar(20), #plantid char(1) AS DECLARE #dynamicSQL varchar(8000) DECLARE #datemth char(6) DECLARE #dateday char(2) DECLARE #FXTIME char(4) DECLARE #TBL varchar(20) DECLARE #def varchar(20) DECLARE #OUTDAT CHAR(20) SET #datemth = substring(#qaaprvdt,1,6) SET #dateday = substring(#qaaprvdt,7,2) IF #flg = 'QA' AND #dbo = 'PRCDAILYQA' BEGIN SET #TBL = 'DAILYQA' SET #OUTDAT = 'CO.QAAPRVDT' END IF #plantid = '1' BEGIN SET #def = "SQDPRCDEF1" END IF #flg = 'QA' AND #plantid = '1' BEGIN SET #dynamicSQL = 'insert into PrcdailyQA' + '(process, seqno, qaamon, qaaday, orderno, ingotno, theopcs, cwacc, pwacc, pwout, procyld, prodyld, plantid, prodline) ' + '(SELECT distinct(b.PROCNO), b.proseq, "' + #datemth + '" , "' + #dateday + '", a.orderno, a.ingotno, a.theopcs, a.cwacc, a.pwacc, a.pwout, a.COprocyld, a.COprodyld, a.plantid, a.prodline ' + 'FROM DailyQA a , SQDPRCDEF1 b ' + 'WHERE a.qaamon = ' + #datemth + ' and a.qaaday= ' + #DATEDAY + ' and a.plantid="1"' + 'GROUP BY b.procno, b.proseq, a.orderno, a.ingotno, a.theopcs, a.cwacc, a.pwacc, a.pwout, a.COprocyld, a.COprodyld, a.plantid, a.prodline) ' Now when I to execute it returns no error. But when I try to execute it at runtime, it returns error Msg 164, Level 15, State 1, Line 1 Each GROUP BY expression must contain at least one column that is not an outer reference. I already refer this http://www.sql-server-performance.com/2007/group-by-expression-contain-one-column-not-an-outer-reference/ and try to change the group by statement, also return error. Please help!
Because you are not aggregating on any fields (i.e. using sum, max, etc.), you don't really need to use a group by clause in your example. However, what are you trying to do in the from clause? You are currently creating a cartesian product of the 2 tables -- you aren't joining the tables on any common field. Without knowing more, I'd be more inclined to remove the group by clause altogether, and have something like this: insert into ... select distinct b.PROCNO, b.proseq, ... from ... where ... Btw, in general I wouldn't recommend using commas in a from clause, use join instead.
You don't need DISTINCT in a GROUP BY query. Also, you are selecting columns which do not either appear in the GROUP BY clause or are aggregates of columns. Removing DISTINCT along with the non-aggregate columns would leave you with the following query: INSERT INTO PrcdailyQA (process, seqno, qaamon, qaaday, orderno, ingotno, theopcs, cwacc, pwacc, pwout, procyld, prodyld, plantid, prodline) SELECT b.PROCNO, b.proseq, a.orderno, a.ingotno, a.theopcs, a.cwacc, a.pwacc, a.pwout, a.COprocyld, a.COprodyld, a.plantid, a.prodline FROM DailyQA a, SQDPRCDEF1 b WHERE a.qaamon = ' + #datemth + ' AND a.qaaday = ' + #DATEDAY + ' AND a.plantid = "1"' GROUP BY b.procno, b.proseq, a.orderno, a.ingotno, a.theopcs, a.cwacc, a.pwacc, a.pwout, a.COprocyld, a.COprodyld, a.plantid, a.prodline
Autogenerate numbers based on "Group" in GroupByExpression RadGrid and display it in RadGrid
I am having a trouble in implementing below requirement. Current RadGrid: Below is the RadGrid in which I am using GroupByExpressions to display/show data grouped with "Business Unit" column. In RadGrid column 2nd(InvoiceLineNo) and 3rd(InvoiceNo), I am auto generating the numbers using Stored Procedure. i.e., for "InvoiceLineNo" column, Autogenerated No's are: 01,02,03,04,05,06,07,08.......n for "InvoiceNo" column, Autogenerated No's are: 15100001, 15100002, 15100003........n where, 15 is a "year" and 100001 are "running numbers" Requirement is: I want to show the "InvoiceLineNo" column data as Group wise. Example: for 1st "Business Unit" group (i.e., SUNWAY LEISURE SDN BHD (CARNIVAL)), InvoiceLineNo shall be: 01,02,03,04,05,06,07,08 for 2nd "Business Unit" group (i.e., SUNWAY MALL PARKING SDN BHD), InvoiceLineNo shall be: 01,02,03,04,05,06,07,08 Similarly, I want to show the "InvoiceNo" column data as Group wise. Example: for 1st "Business Unit" group (i.e., SUNWAY LEISURE SDN BHD (CARNIVAL)), InvoiceNo shall be: 15100001,15100001,15100001,15100001,15100001,15100001,15100001,15100001 for 2nd "Business Unit" group (i.e., SUNWAY MALL PARKING SDN BHD), InvoiceNo shall be: 15100002,15100002,15100002,15100002,15100002,15100002,15100002,15100002 "InvoiceNo" column data will always be unique for different "Business Unit". I want output to be like below snapshot: I can autogenerate the numbers serial wise but I am not getting how to autogenerate the 2 column values based on Group and show them like that. Please help me to achieve it. Please do reply. Thanks in advance. Edit: Below is the Stored Procedure I am using to generate autogenerated numbers in RadGrid's 2 column's: ALTER PROCEDURE [dbo].[SDM_Assign_RunningNo] -- Add the parameters for the stored procedure here #TableName as nvarchar(50), #NewID as nvarchar(50) OUTPUT AS BEGIN -- SET NOCOUNT ON added to prevent extra result sets from -- interfering with SELECT statements. SET NOCOUNT ON; DECLARE #rn_year as nvarchar(50) --Get Year From table SELECT #rn_year =RNYear FROM dbo.SDM_Tran_RunningNo WHERE RNYear= YEAR(GetDate()) --get last 2 digits of year Declare #2digit_rn_year as nvarchar(50) SELECT #2digit_rn_year = RNYear % 100 FROM dbo.SDM_Tran_RunningNo WHERE RNYear= YEAR(GetDate()) IF #TableName='SDM_Tran_GenerateInvoice_No' BEGIN SELECT #NewID=Next_InvoiceNo FROM dbo.SDM_Tran_RunningNo WHERE RNYear=#rn_year UPDATE dbo.SDM_Tran_RunningNo SET Next_InvoiceNo=Next_InvoiceNo+1 WHERE RNYear=#rn_year SET #NewID = #2digit_rn_year +'1'+RIGHT('000000' + CAST(#NewID as varchar(10)), 5) END ELSE IF #TableName='SDM_Tran_GenerateInvoice_LineNo' BEGIN SELECT #NewID=Next_InvoiceLineNo FROM dbo.SDM_Tran_RunningNo WHERE RNYear=#rn_year UPDATE dbo.SDM_Tran_RunningNo SET Next_InvoiceLineNo=Next_InvoiceLineNo+1 WHERE RNYear=#rn_year SET #NewID = RIGHT('000000' + CAST(#NewID as varchar(10)), 2) END END And then inserting the 2 column values into Table as below (using Stored Procedure), to display it in RadGrid: DECLARE #InvoiceNo as nvarchar(50) --SP to generate new Invoice No EXEC dbo.SDM_Assign_RunningNo #TableName='SDM_Tran_GenerateInvoice_No', #NewID = #InvoiceNo OUTPUT DECLARE #InvoiceLineNo as nvarchar(50) --SP to generate new Invoice Line No EXEC dbo.SDM_Assign_RunningNo #TableName='SDM_Tran_GenerateInvoice_LineNo', #NewID = #InvoiceLineNo OUTPUT INSERT INTO SDM_Tran_GenerateInvoice VALUES (#InvoiceID, #SPfoID, #InvoiceLineNo, #InvoiceNo, #InvoiceType, #BillingIDfoID, #BusinessUnit, #DirectCost, #Status, GETDATE(), #AccountCode)
This is a concept... you might need to modify it to suit your requirement. DECLARE #Temp TABLE ( InvoiceID nvarchar(50), SPfoID nvarchar(50), InvoiceLineNo nvarchar(50), InvoiceNo nvarchar(50), InvoiceType nvarchar(50), BillingIDfoID nvarchar(50), BusinessUnit nvarchar(2000), DirectCost nvarchar(2000), Status nvarchar(10), Date datetime, AccountCode nvarchar(1000) ) DECLARE #Temp1 TABLE ( OrderID INT IDENTITY, -- Added This so It Will follow this new Identity Row InvoiceID nvarchar(50), SPfoID nvarchar(50), InvoiceLineNo nvarchar(50), InvoiceNo nvarchar(50), InvoiceType nvarchar(50), BillingIDfoID nvarchar(50), BusinessUnit nvarchar(2000), DirectCost nvarchar(2000), Status nvarchar(10), Date datetime, AccountCode nvarchar(1000) ) DECLARE #CompanyValue nvarchar(2000) = '' --BusinessUnit datatype DECLARE #Counter nvarchar(50) = '0' --InvoiceNo datatype DECLARE #InvoiceLine INT = 1 DECLARE #Year INT = YEAR(GETDATE()) DECLARE #ShortYear VARCHAR(2) = SUBSTRING(CONVERT(VARCHAR(4), #Year), 3, 2) EXEC dbo._RunningNo #TableName='Invoice', #NewID = InvoiceID --OUTPUT INSERT INTO #Temp (InvoiceID, SPfoID, InvoiceType, BillingIDfoID, BusinessUnit, DirectCost, Status, Date, AccountCode) SELECT InvoiceID, SPfoID, InvoiceType, BillingIDfoID, BusinessUnit, DirectCost, Status, Date, AccountCode FROM [MainTable] ORDER BY BusinessUnit INSERT INTO #Temp1 SELECT * FROM #Temp ORDER BY BusinessUnit SELECT * FROM #Temp SELECT * FROM #Temp1 -- before update --Update #Temp1 table UPDATE #Temp1 SET #Counter = InvoiceNo = CASE WHEN #CompanyValue = '' OR #CompanyValue = BusinessUnit THEN (CONVERT(VARCHAR(100), CONVERT(INT,#Counter) + 1)) ELSE '1' END, #InvoiceLine = CASE WHEN #CompanyValue = '' OR #CompanyValue = BusinessUnit THEN #InvoiceLine ELSE #InvoiceLine + 1 END, #CompanyValue = BusinessUnit, InvoiceLineNo = #ShortYear + '10000' + CONVERT(VARCHAR(3), #InvoiceLine) SELECT * FROM #Temp1 --after update --Update main table UPDATE g SET g.InvoiceLineNo = t.InvoiceLineNo, g.InvoiceNo = t.InvoiceNo FROM SDM_Tran_GenerateInvoice g INNER JOIN #Temp1 t ON g.InvoiceID = t.InvoiceID Select * from [MainTable] ORDER BY BusinessUnit;
Temp table not being created
I'm trying to create 2 temp tables in the following code. Though my condition says to create temp table from the else statement, for tmp2 it is saying table already created. I'm doing this because I want to union the data from 2 temp tables whether it has data or not. The following script is not creating ##tmp2 table irrespective of the else condition in the following query... DECLARE ##TOTALCOUNT INT DECLARE ##DECRIPTION VARCHAR(100) DECLARE ##ST VARCHAR(100) DECLARE ##ZP VARCHAR(100) DECLARE ##CT VARCHAR(100) DECLARE ##GN VARCHAR(100) SET ##ST = 'IA' SET ##CT = 'JOHNSTON' SET ##ZP = '50131' SET ##GN = 'FEMALE' BEGIN TRY DROP TABLE ##TMP1; DROP TABLE ##TMP2; END TRY BEGIN CATCH SET ##DECRIPTION = ' VEHICLES ARE SOLD DURING LAST 3 MONTHS ' SET ##TOTALCOUNT = ( SELECT COUNT(*) FROM [TALK TRACK RAP].DBO.CARSEXCEL WHERE [SALE_DATE] > DATEADD( DAY, -90 ,CONVERT (DATE , '01/01/2013',103)) AND [SALE_DATE] < CONVERT (DATE , '01/01/2013',103)) ; SELECT MAKE , ( (100 * COUNT(*)) /##TOTALCOUNT ) CN , CONVERT(VARCHAR, ( (100 * COUNT(*)) /##TOTALCOUNT ))+ ' % ' + MAKE + ##DECRIPTION AS TALK INTO ##TMP1 FROM [TALK TRACK RAP].DBO.CARSEXCEL WHERE [SALE_DATE] > DATEADD( DAY, -90 ,CONVERT (DATE , '01/01/2013',103)) AND [SALE_DATE] < CONVERT (DATE , '01/01/2013',103) GROUP BY MAKE END CATCH IF ##ST IS NULL BEGIN SET ##TOTALCOUNT = (SELECT COUNT(*) FROM [TALK TRACK RAP].DBO.CARSEXCEL WHERE [SALE_DATE] > DATEADD( DAY, -90 ,CONVERT (DATE , '01/01/2013',103)) AND [SALE_DATE] < CONVERT (DATE , '01/01/2013',103) AND STATE= ##ST ) SET ##DECRIPTION = ' VEHICLES ARE SOLD DURING LAST 3 MONTHS IN ' + ##ST+ ' STATE ' SELECT MAKE , ( (100 * COUNT(*)) / ##TOTALCOUNT ) CN , CONVERT(VARCHAR, ( (100 * COUNT(*)) /##TOTALCOUNT ))+ ' % ' +MAKE + ##DECRIPTION AS TALK INTO ##TMP2 FROM [TALK TRACK RAP].DBO.CARSEXCEL WHERE [SALE_DATE] > DATEADD( DAY, -90 ,CONVERT (DATE , '01/01/2013',103)) AND [SALE_DATE] < CONVERT (DATE , '01/01/2013',103) AND STATE= ##ST GROUP BY MAKE ; END if ##ST IS NOT NULL BEGIN IF EXISTS ( SELECT * FROM sys.tables WHERE name LIKE '##TMP2%' ) DROP TABLE ##TMP2 CREATE TABLE ##TMP2 (MAKE VARCHAR(30), CN VARCHAR(30), TALK VARCHAR(30)) END How can I fix this?
Temporary tables don't show up in sys.tables. Here's a simple way to test for a temp table: IF OBJECT_ID('tempdb..#TMP2') IS NOT NULL DROP TABLE #TMP2 GO
Inserting concatenated values in T-SQL
Ok, this is what I am trying to achieve: My script below is supposed to gather values across three tables and insert them in TO TABLE B in sequence. There are two columns that are being affected in TABLE B the INDXLONG AND DDLINE. In The DDLINE row I am attempting to concatenate values from different fields and to store them as one. My code is below. Please share any insights: Declare #nRowCount int, #Indxlong int, #hdrLOCAL char(255), #CR char(255), #BLDCHKDT DATETIME, #BLDCHTIME DATETIME, #hdrline int, #1strowline int, #2ndrowline int, #3rdrowline int, #BWP char(255), #CompAcc char(11), #BankCode char(11), #BranchNo char(11), #PayDate datetime, #Reference char(11), #TotaAmt numeric(19,5) #CoName char(11), #BeneficiaryAcc char(11), #BenBankBranchCode char(11), #Salary numeric (19,5), #BeneficiaryName char(23), #TransRef char(23), #outer_c int SELECT #CompAcc =DDCOIDEN, #BankCode =DDIMORIG, #BranchNo =DDIMDEST, #Reference =DDDESC10, #CoName =DDIMORNM FROM TABLE A Declare ACH SCROLL CURSOR FOR SELECT T762.DDINDNAM, T762.DDTRANUM, T762.DDACTNUM, T762.DDAMTDLR, T756.PAYDATE FROM STATS.dbo.TABLE C T762 LEFT OUTER JOIN STATS.dbo.TABLE D T756 ON ( T762.INDXLONG = T756.INDXLONG AND T756.INCLPYMT = 1 ) WHERE (T756.INCLPYMT = 1) AND (T762.DDAMTDLR <> 0) FOR READ ONLY; OPEN ACH; SET NOCOUNT ON; FETCH FROM ACH INTO #BeneficiaryName,#BenBankBranchCode,#BeneficiaryAcc,#Salary,#paydate WHILE ##FETCH_STATUS = 0 BEGIN Select #TotaAmt =SUM(#Salary) set #hdrline =1 set #1strowline =2 set #2ndrowline =3 set #3rdrowline =9 SELECT #hdrLOCAL = DDLINE FROM TABLE E WHERE INDXLONG =1 SELECT #CR = DDLINE FROM TABLE E WHERE INDXLONG =2 SELECT #BWP = DDLINE FROM TABLE E WHERE INDXLONG =3 BEGIN INSERT INTO TABLE B (INDXLONG,DDLINE) VALUES (1,#hdrLOCAL + ',' + #CR + ',' ) SELECT ##IDENTITY END BEGIN INSERT INTO TABLE B (INDXLONG,DDLINE) VALUES (2,#CompAcc + #BranchNo +','+ #BWP+ ',' + #PayDate +',' + #Reference + ','+#TotaAmt + ','+ #TransRef) SELECT ##IDENTITY END BEGIN INSERT INTO TABLE B (INDXLONG,DDLINE) VALUES (3,#BeneficiaryAcc + ',' + #BenBankBranchCode +','+ #BeneficiaryAcc+ ',' + #Salary +',' + #Reference + ','+#TotaAmt + ','+ #TransRef) SELECT ##IDENTITY END FETCH FROM ACH INTO #BeneficiaryName,#BenBankBranchCode,#BeneficiaryAcc,#Salary,#paydate END CLOSE ACH DEALLOCATE ACH SET NOCOUNT OFF; This is the error: Msg 8152, Level 16, State 14, Line 69 String or binary data would be truncated. The statement has been terminated. Msg 241, Level 16, State 1, Line 74 Conversion failed when converting date and/or time from character string. This is the result I am aiming for: INDXLONG DDLINE ----------- ----------------------------------------------------------------------- 1 101001 029 1403200610A094101 AMEN BANK LOVE 2 123456 111 34567 PPDSALARYPAYT140131140117 11234567 3 63206623 0101962706200 0000062709000319614 ADAMS EVE
Cast your dates into varchars/nvarchars if you are going to concatenate them. For examples, #PayDate should be casted like this: cast(PayDate as varchar(20)). Or if you need the date in a specific format, use Convert.