OUTPUT TO MULTIPLE FILES FROM A SINGLE QUERY - sql-server-2008

I am a little stuck... I am trying to take the output from a query and break it into numerous files based on a single criteria. I am getting an error of converting a varchar type to int and I cannot figure out why. Working in SQL Server 2008...
DECLARE #LOOP AS INT;
DECLARE #SQL AS VARCHAR(MAX);
DECLARE #BCP AS VARCHAR(MAX);
DECLARE #COUNTER AS INT;
DECLARE #FILENAME AS VARCHAR(MAX);
SET #COUNTER='1'
SELECT #LOOP = COUNT(DISTINCT LIST_ID) FROM DATA_TABLE
WHERE STATUS='2' AND LIST_ID IS NOT NULL ;
SET #SQL=(SELECT CUSTOMER_NO FROM CUSTOMER A, DATA_TABLE B
WHERE A.CUSTOMER_ID=B.CUSTOMER_ID AND A.STATUS='2' AND LIST_ID='+#LOOP+');
SET #FILENAME='QUERYOUT C:\Projects\FILE_"'+#LOOP+'.TXT'
WHILE #COUNTER<=#LOOP
BEGIN
SELECT
#BCP='BCP "'+#SQL+'+'+#FILENAME+''
SET #COUNTER=#COUNTER+1
END
GO
The error I am getting is:
Msg 245, Level 16, State 1, Line 10
Conversion failed when converting the varchar value '+#LOOP+' to data type int.
I am trying to use the LOOP value to let me know the contents of each file. For example, LOOP='1' would mean the file contains the customer records associate with LIST_ID='1'
Thoughts on the error?

I'm not sure I understand exactly what you need but if you want to issue the BCP command for every LIST_ID you need to loop though them and execute for each one.
This may not be what you need but rather than wait until I am home from work I will post it now.
DECLARE #FILENAME AS VARCHAR(MAX);
DECLARE #LISTID INT
DECLARE #LOOP AS INT;
DECLARE #BCP AS VARCHAR(MAX);
DECLARE #SQL AS VARCHAR(MAX);
DECLARE cur CURSOR FOR SELECT DISTINCT LIST_ID FROM DATA_TABLE WHERE STATUS='2' AND LIST_ID IS NOT NULL
OPEN cur
FETCH NEXT FROM cur INTO #LISTID
WHILE ##FETCH_STATUS = 0 BEGIN
SET #FILENAME='QUERYOUT C:\Projects\FILE_'+Cast(#LISTID AS Varchar)+'.TXT -c -t -T'
SET #SQL='(SELECT CUSTOMER_NO FROM CUSTOMER A, DATA_TABLE B WHERE A.CUSTOMER_ID=B.CUSTOMER_ID AND A.STATUS=''2'' AND LIST_ID='+#LISTID+')';
SELECT #BCP='BCP '+#SQL+' '+#FILENAME+''
EXEC xp_cmdshell #BCP
FETCH NEXT FROM cur INTO #LISTID
END
CLOSE cur
DEALLOCATE cur

1.change varchar(max) to varchar(8000)
2.Add DBNAME.SCHEMA for all the tables, because by default it will point to the Master db.
Added double quotes(") below
3. #FILENAME='QUERYOUT "C:\Projects\FILE_'+Cast(#LISTID AS Varchar)+'.TXT" -c -t -T'
4. '("SELECT CUSTOMER_NO FROM CUSTOMER A, DATA_TABLE B WHERE A.CUSTOMER_ID=B.CUSTOMER_ID AND A.STATUS=''2'' AND LIST_ID='+#LISTID+'")';

Related

sql trigger unable to set variable from select

I know its asked question ,however I have tried few amendments but to no solution .
My trigger:
BEGIN
DECLARE bookid INT;
DECLARE roomtype varchar(20);
DECLARE amount INT;
DECLARE m_count INT;
DECLARE curr_m varchar(20);
SET #bookid := NEW.id;
SET roomtype := (SELECT title FROM pm_booking_room WHERE id_booking=#bookid);
SET amount := (SELECT amount from pm_booking_payment WHERE id_booking=#bookid);
SET #curr_m:= (MONTHNAME(NOW()));
SET #m_count:= (SELECT count(*) FROM pm_report WHERE month=#curr_m);
INSERT INTO `pm_report`(`month`, `room_type`, `amount`) VALUES(#curr_m,#roomtype,#amount);
END
whwn I check table, it inserts, but only #curr which is month name. Rest it inserts NULL
I tried
SET #roomtype SELECT title FROM pm_booking_room WHERE id_booking=#bookid but still same,NULL .
Also tried SET #roomtype := (SELECT title FROM pm_booking_room WHERE id_booking=#bookid); but still NULL.
I am using PhpMyadmin to create :
Please help.
Please be aware that roomtype and #roomtype are two different variables.
The variables you declare with the local variable DECLARE statement have a scope within the body of one stored routine. They are never spelled with a # sigil.
The user-defined variables with the # sigil have a scope of a MySQL session. You don't need to declare these kinds of variables. Just setting the variable to a value implicitly creates the variable.
You cannot SET roomtype = ... and expect that string to be read from the #roomtype variable. Nor vice-versa.
You appear to declare local variables, so you should use them consistently. But in some cases, your variable names are the same as column names, which will result in ambiguity if you use the variables in SQL statements that also reference tables with those columns. So you should adopt a naming convention to keep them distinct.
BEGIN
DECLARE v_bookid INT;
DECLARE v_roomtype varchar(20);
DECLARE v_amount INT;
DECLARE v_count INT;
DECLARE v_month varchar(20);
SET v_bookid := NEW.id;
SET v_roomtype := (SELECT title FROM pm_booking_room WHERE id_booking=v_bookid);
SET v_amount := (SELECT amount from pm_booking_payment WHERE id_booking=v_bookid);
SET v_month:= (MONTHNAME(NOW()));
SET v_count:= (SELECT count(*) FROM pm_report WHERE month=v_month);
INSERT INTO `pm_report`(`month`, `room_type`, `amount`) VALUES(v_month,v_roomtype,v_amount);
END
(This code is not tested, so apologies if there are any mistakes. It is meant only to demonstrate using non-sigil variables consistently.)

How to combine single column value from many row by loop

When I run my first query, I get 5 rows of result. The value for row1 is "Day1", row 2 is "Day2" and etc... After that I want combine it to a string as "Day1,Day2,Day3,Day4,Day5". But after I run the stored procedure, I get empty result. Below is my stored procedure. How to I solve it? Thanks
SET NOCOUNT ON
Declare #PeriodID nvarchar(50);
Declare #FinalString nvarchar(80);
DECLARE vendor_cursor CURSOR FOR
SELECT PeriodID FROM PeriodTable c WHERE c.Active=1
OPEN vendor_cursor
FETCH NEXT FROM vendor_cursor
INTO #PeriodID
WHILE ##FETCH_STATUS = 0
BEGIN
SELECT #FinalString = #FinalString + #PeriodID + ','
FETCH NEXT FROM vendor_cursor
INTO #PeriodID
END
CLOSE vendor_cursor;
DEALLOCATE vendor_cursor;
print #FinalString
SET NOCOUNT OFF
No need for a cursor. I think you missed setting the variable to a blank string first so it was null making each row null. This works:
declare #ret varchar(8000)
set #ret = ''
select #ret = #ret+', '+name
from ImagedApps
order by name
-- take off the first comma and space
select substring(#ret, 3, 8000)

SSRS Pivot Expression Inside Stored Procedure with HashTemp Not Running

While Working With SSRS, Today, i got 2 Problems 1 is Still remain Unsolved and Im going to Post Another Freaking Problem :) Well, Problem is : I've an Stored Procedure, Which Create an #Temp and Finally Use that data with PIVOT Expression. And, Stored Procedure itself runs Fine inside SSMS and From Visual Basic 6.0 too, but While Using that Procedure from SSRS report it shows an error at the Pivot Expression. Following are the Screen Shots, Please Review and Suggest me an Idea.
Here is an Stored Procedure :
ALTER PROCEDURE [dbo].[S_NRB_9_8_REPORT](#SCRCODE AS VARCHAR(20),
#CUREDATE VARCHAR(10),
#DTNAME VARCHAR(50),
#BR_CODE VARCHAR(50),
#CENTRALIZED VARCHAR(3))
WITH RECOMPILE
AS BEGIN
SET NOCOUNT ON;
DECLARE #BRCODE VARCHAR(3)
DECLARE #DTBASE VARCHAR(50)
DECLARE #CAT_TYPE_CODE VARCHAR(50)
DECLARE #AC_TYPE_SUB_TYPE_NAME VARCHAR(200)
DECLARE #CODESTR VARCHAR (1000)
DECLARE #CODESTR1 VARCHAR (1000)
SET #BRCODE=''
SET #DTBASE=''
SET #AC_TYPE_SUB_TYPE_NAME=''
SET #CODESTR=''
SET #CODESTR1=''
SELECT TOP 1 #CAT_TYPE_CODE=CAT_TYPE_CODE FROM REPORT_CAT_TYPE_CODE WHERE SCREEN_CODE =#SCRCODE
IF #CAT_TYPE_CODE='' OR #CAT_TYPE_CODE IS NULL
RETURN
CREATE TABLE [dbo].[#TEMPACTYPE](
[BR_CODE] [varchar](3) NULL,
[CN] [varchar](50) NULL,
[CS] [varchar](50) NULL,
[BAL] decimal(18, 2) NULL,
[AC_TYPE_SUB_TYPE_NAME] [varchar](50) NULL
) ON [PRIMARY]
IF LEN(#BR_CODE)>0
EXEC('DECLARE CUR INSENSITIVE CURSOR FOR SELECT BR_CODE FROM '+#DTBASE+'.DBO.BRANCH B (NOLOCK) WHERE BR_CODE='''+#BR_CODE+''' AND INTEGRATED=''YES'' AND APPROVED=''YES'' ORDER BY BR_CODE')
ELSE
EXEC('DECLARE CUR INSENSITIVE CURSOR FOR SELECT BR_CODE FROM '+#DTBASE+'.DBO.BRANCH B (NOLOCK) WHERE INTEGRATED=''YES'' AND APPROVED=''YES'' ORDER BY BR_CODE')
OPEN CUR
FETCH NEXT FROM CUR INTO #BRCODE
While ##FETCH_STATUS = 0
Begin
IF #CENTRALIZED='YES'
SET #DTBASE = #DTNAME
ELSE
SET #DTBASE = Left(#DTNAME, 13) + #BRCODE
EXEC('INSERT INTO #TEMPACTYPE
SELECT '''+#BRCODE+''' AS BR_CODE,T1.CAT_NAME AS CN,T1.CODES AS CS,SUM(T1.C_BAL)AS BAL,T1.AC_TYPE_SUB_TYPE_NAME FROM
(SELECT C_BAL,ATST.AC_TYPE_SUB_TYPE_NAME,CD.CAT_NAME,CD.CODE_STRING AS CODES
FROM
(SELECT AC_GROUP_CODE,CUR_CODE,GL_CODE FROM '+#DTBASE+'.dbo.AC_GROUP_GL_MAP WHERE NAMED_AC_CODE =''0301'') MAP,
(SELECT AC_GROUP_CODE,CUR_CODE,AC_NO FROM '+#DTBASE+'.dbo.DEPOSIT_AC_MAST WHERE BR_CODE='''+#BRCODE+''') DAM,
(SELECT TRAN_DATE,AC_NO,GL_CODE,PRODUCT_CODE,SUM(CLS_BAL) AS C_BAL FROM '+#DTBASE+'.dbo.AC_BAL WHERE BR_CODE='''+#BRCODE+''' GROUP BY TRAN_DATE,AC_NO,GL_CODE,PRODUCT_CODE) WD,
(SELECT * FROM '+#DTBASE+'.dbo.CAT_CODING where BR_CODE='''+#BRCODE+''' AND CAT_TYPE_CODE ='''+#CAT_TYPE_CODE+''') AS CC,
(SELECT * FROM '+#DTBASE+'.dbo.AC_TYPE_SUB_TYPE) AS ATST,
(SELECT * FROM '+#DTBASE+'.dbo.AC_GROUP) AS AG,
(SELECT * FROM '+#DTBASE+'.dbo.CAT_DETL) AS CD
WHERE
DAM.AC_GROUP_CODE =MAP.AC_GROUP_CODE
AND DAM.CUR_CODE =MAP.CUR_CODE
AND WD.GL_CODE =MAP.GL_CODE
AND CC.ENTITY_NO=DAM.AC_NO
AND ATST.AC_TYPE_CODE=AG.AC_TYPE_CODE
AND ATST.AC_TYPE_SUB_TYPE_CODE=AG.AC_TYPE_SUB_TYPE_CODE
AND AG.AC_GROUP_CODE=DAM.AC_GROUP_CODE
AND CD.CAT_TYPE_CODE=CC.CAT_TYPE_CODE
AND CD.CAT_CODE=CC.CAT_CODE
AND CD.CAT_TYPE_CODE='''+#CAT_TYPE_CODE+'''
AND WD.TRAN_DATE = (SELECT MAX(TRAN_DATE) FROM '+#DTBASE+'.dbo.AC_BAL WHERE BR_CODE ='''+#BRCODE+''' AND AC_NO = DAM.AC_NO AND TRAN_DATE <='''+#CUREDATE+''' AND GL_CODE=MAP.GL_CODE)
AND DAM.AC_NO=WD.AC_NO
UNION ALL
SELECT 0,ATST.AC_TYPE_SUB_TYPE_NAME,CAT_NAME,CODE_STRING AS CODES FROM '+#DTBASE+'.dbo.CAT_DETL AS CD,'+#DTBASE+'.dbo.AC_TYPE_SUB_TYPE AS ATST
WHERE CAT_TYPE_CODE='''+#CAT_TYPE_CODE+''' AND CAT_CODE NOT IN (SELECT CAT_CODE FROM '+#DTBASE+'.dbo.CAT_CODING WHERE BR_CODE='''+#BRCODE+''' AND CAT_TYPE_CODE='''+#CAT_TYPE_CODE+''')
AND ATST.AC_TYPE_CODE=''03''
) T1
GROUP BY T1.AC_TYPE_SUB_TYPE_NAME,CAT_NAME,CODES
ORDER BY CODES
')
FETCH NEXT FROM CUR INTO #BRCODE
END
DEALLOCATE CUR
DECLARE CUR INSENSITIVE CURSOR FOR SELECT DISTINCT AC_TYPE_SUB_TYPE_NAME FROM #TEMPACTYPE
OPEN CUR
Fetch Next from CUR Into #AC_TYPE_SUB_TYPE_NAME
While ##FETCH_STATUS = 0
Begin
IF #CODESTR =''
BEGIN
SET #CODESTR = 'ISNULL(['+#AC_TYPE_SUB_TYPE_NAME+'],0) AS ['+#AC_TYPE_SUB_TYPE_NAME+']'
SET #CODESTR1 = '['+#AC_TYPE_SUB_TYPE_NAME+']'
END
ELSE
BEGIN
SET #CODESTR = #CODESTR+',ISNULL(['+#AC_TYPE_SUB_TYPE_NAME+'],0) AS ['+#AC_TYPE_SUB_TYPE_NAME+']'
SET #CODESTR1 = #CODESTR1+',['+#AC_TYPE_SUB_TYPE_NAME+']'
END
Fetch Next from CUR Into #AC_TYPE_SUB_TYPE_NAME
END
DEALLOCATE CUR
EXEC ('Select CS,CN,'+#CODESTR+',TOTAL
from (Select CN,CS,BAL,[AC_TYPE_SUB_TYPE_NAME] from #TEMPACTYPE) ps pivot (SUM([BAL])
for [AC_TYPE_SUB_TYPE_NAME] in ('+#CODESTR1+',TOTAL)) pvt
Order by CS')
DROP TABLE #TEMPACTYPE
END
GO
And, the Dataset Design Panel :
But, Stored Procedure Runs Well inside SSMS :
Im Using SSRS 2008 R2.
Please Help me out.
And, Thanks In Advance.
Try validating that you are passing the same parameter values between the report and SSMS. You can do this by clicking Edit Query and inputting the actual parameter values. If the Edit Query window returns proper results, then you are probably passing different values to the stored procedure.

Initializing table name to be used in a stored procedure in SQL Server

I am trying to create a stored procedure to achieve the following in the stored procedure
DECLARE #TBLNAME VARCHAR(128)
SET #TBLNAME = SELECT PAR_VALUE FROM DBO.PARAMETERS WHERE PAR_NAME='SALES_ORDERS_TABLE';
The PAR_VALUE column in the PARAMETERS table contains the name of the table of the Sales Order table.
I now want to use this table name in the stored procedure, and count the number of rows in this table.
DECLARE #SQL NVARCHAR(4000)
# SQL = SELECT COUNT(*) FROM '[#TBLNAME]'
However, when I try to run this, there are multiple errors.
Can you please help me by guiding on how to do this?
I just now tried this code:
CREATE PROCEDURE JCOUNT_SO
AS
DECLARE #TBLNAME NVARCHAR(512)
SELECT #TBLNAME=(SELECT PAR_VALUE FROM DBO.PARAMETERS WHERE PAR_NAME='SALES_ORDERS_TABLE')
DECLARE #SQL NVARCHAR(4000)
SELECT #SQL='SELECT COUNT(*) AS #_OF_RECORDS INTO SO_COUNT
FROM' '+QUOTENAME(#TBLNAME)''
EXEC SP_EXECUTESQL #SQL;
Error Message: Invalid Object Name: 'TEST.DBO.SO_MASTER'
Please help on this code.
Please read defination of sp_executesql for reference. Procedure below returns value as an output parameter from dynamic query rather than inserting into a table. You can manipulate query as per your requirement.
CREATE PROCEDURE JCOUNT_SO
AS
DECLARE #TBLNAME nvarchar(512)
--Obtain table name. Top 1 is used to pick first record rather than last record in case query returns more than one record.
SELECT TOP 1 #TBLNAME = PAR_VALUE FROM DBO.PARAMETERS WHERE PAR_NAME='SALES_ORDERS_TABLE'
DECLARE #SQL NVARCHAR(4000)
DECLARE #Count int
SET #SQL ='SELECT #Count = COUNT(*) FROM ' + #TBLNAME
--Define parameters to be passed i.e. #Count is being passed as output parameter
EXEC SP_EXECUTESQL #SQL, N'#Count int OUTPUT', #Count output
select #Count
end
Notes from MSDN
Query i.e. #SQL can contain parameters having the same form as a variable name and each parameter included in #SQLmust have a corresponding entry in both the #params parameter definition list and the parameter values list
1 point I can say is ... it should be SET #SQL = SELECT ...
and one more thing is you can try converting the result to NVARCHAR.
use SELECT Convert(NVARCHAR(4000),Count(*)) FROM ...

Mysql FETCH CURSOR result ununderstood

I've been Googleing around for a while and I am sure that the problem is that I don't understand clearly how CURSORs in MySQL work.
A short explanation of the problem: I'm writing such function (simplified):
CREATE DEFINER=`me`#`localhost` FUNCTION `product_move`(prID INT, tr_type VARCHAR(2), clID INT, am INT, dnID INT, usrID INT, price FLOAT(10,2), ti DATETIME, barc TINYTEXT, cmt TINYTEXT, lnID INT)
BEGIN
DECLARE done INT DEFAULT FALSE;
DECLARE cur_id INT;
DECLARE net_pr FLOAT(10,2);
DECLARE cur_r INT;
DECLARE remaind INT DEFAULT 0;
DECLARE avg_price FLOAT(10,2) DEFAULT 0;
DECLARE curs CURSOR FOR SELECT `products_transactionsID`,
`price`,
`remains`
FROM `products_transactions`
WHERE `productID`=prID AND `remains`>0 AND `type`='V'
ORDER BY `products_transactionsID` ASC;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
OPEN curs;
SET remaind=am;
read_loop:LOOP
FETCH curs INTO cur_id,net_pr,cur_r;
IF done THEN
LEAVE read_loop;
END IF;
IF (cur_r>=remaind) THEN
SET avg_price = avg_price + (net_pr * remaind);
UPDATE `products_transactions` SET `remains`=`remains`-remaind WHERE products_transactionsID=cur_id;
LEAVE read_loop;
ELSE
SET avg_price = avg_price + (net_pr * cur_r);
SET remaind=remaind-cur_r;
UPDATE `products_transactions` SET `remains`=0 WHERE products_transactionsID=cur_id;
END IF;
END LOOP;
CLOSE curs;
SET avg_price=avg_price/am;
INSERT INTO products_transactions
(`products_transactionsID`,`clientID`,`date_created`,`delivery_notesID`,`type`,`productID`,`amountIN`,`amountOUT`,`barcodes`,`in_stock`,`out_stock`,`out_repair`,`out_loss`,`booked`,`ordered`,`userID`,`price`,`comments`,`fifo_buy_price`)
SELECT NULL, clID, ti, dnID , tr_type, prID, 0, am, barc, products_transactions.in_stock-am, products_transactions.out_stock,
products_transactions.out_repair, products_transactions.out_loss, products_transactions.booked, products_transactions.ordered,usrID,price,cmt,avg_price
FROM
products_transactions WHERE productID=prID ORDER BY products_transactionsID DESC LIMIT 1;
So, we insert a new row in this table, based upon some calculations from the previously selected rows and updating these rows meanwhile.
The problem is with the avg_price variable, which should be calculated based on the net_pr variable which is FETCH'ed from the cursor. But somehow, instead of being FETCH'ed from the SELECT, the net_pr variable takes the value of the price input parameter of my function! How is that possible?
My guesses have been so far:
a variable name conflict? Searched through the code but I can't find any.
updating the table within the LOOP could make the CURSOR loose its position? It would make sense, but that wouldn't result in this, either...
I'd apreciate any ideas.
Two things that I can see:
1) Don't update the table that you're using in the cursor. MySQL says the cursor is read only but I wouldn't trust this. Set your value, exit the cursor, and then update the table.
2) Using the same name for a variable in the proc definition and a column in a select gives a conflict: http://dev.mysql.com/doc/refman/5.0/en/local-variable-scope.html
"A local variable should not have the same name as a table column. If an SQL statement, such as a SELECT ... INTO statement, contains a reference to a column and a declared local variable with the same name, MySQL currently interprets the reference as the name of a variable. "