Table data to json . MSSQL - json

I need to convert table data to Json,
NOTE: i know we can do it easily with the help of Json path like below code
SELECT
divisionId
,Divisionname
,isActive
,Divcode
FROM [dbo].[Division]
FOR JSON PATH,
INCLUDE_NULL_VALUES
GO
But my task is to do same operation with cursor
I wrote cursor its working fine
but how to append Json each time loop rotate
DECLARE
#divisionId INT,
#Divisionname varchar(50),
#isActive bit,
#Divcode int
DECLARE cursor1 CURSOR
FOR SELECT * FROM [dbo].[Division]
--WHERE PlantTypeId=2;
OPEN cursor1;
FETCH NEXT FROM cursor1 INTO #divisionId,#Divisionname,#isActive,#Divcode
WHILE ##FETCH_STATUS = 0
BEGIN
--PRINT cast(#divisionId as varchar)+','+ #Divisionname +','+ cast(#isActive as varchar)+','+#Divcode
PRINT concat( #divisionId,#Divisionname,#isActive,#Divcode)
FETCH NEXT FROM cursor1 INTO
#divisionId,#Divisionname,#isActive,#Divcode
END;
CLOSE cursor1;
DEALLOCATE cursor1;
o/p of courser look like this
2PH110
15AH113
16WF014
17BC115
Completion time: 2022-08-03T16:34:09.1279503+05:30
instead of Print I should implement Json

Related

Store json query output in variable / use variable in ole automation api post?

I have a ole automation query that sends json data to an rest api. This works great when you hardcode the json data in the query.
I am trying to use the output from a for json query instead.
So my basic goal is to store the json from the query output in a usable variable
I have tried this
but null always gets assigned to the variable
```
declare #JsonOutput xml
EXEC SP_EXECUTESQL #SqlText, N'#JsonOutput xml OUTPUT', #JsonOutput = #JsonOutput OUTPUT
```
the above output does return the json but the #JsonOutput variable never gets set with the JSON data and is unusable..
..................
Update:
I found a work around but was still wondering if there was a better way. I'm loading the json into a temp table then selecting it and stores it in a usable variable and it posts successfully. It does however seem to restrict the amount of json I can put in the temp table field.
'''
set nocount on;
drop table #b
;WITH x(a) as
(
select JSON_QUERY(rtrim(JSON_MODIFY('[]', 'append $', authorIds))) AS authorIds,[bases], [isCircular], [name], 'ts_SOThWL5L' [schemaId], [registryId], [namingStrategy]
FROM [dbo].[vw_bulkDNAPostCreate]
where myid between 600 and 630
FOR JSON PATH, ROOT('dnaSequences')
)
SELECT a INTO #b FROM x
select a from #b
DECLARE #IntVariable INT;
DECLARE #SQLString NVARCHAR(500);
DECLARE #ParmDefinition NVARCHAR(500);
DECLARE #JSON varchar(max);
set #SQLString = N'select #JSONOUT = a from #b'
SET #ParmDefinition = N'#JSONOUT varchar(max) OUTPUT';
EXECUTE sp_executesql #SQLString, #ParmDefinition,#JSONOUT=#JSON OUTPUT;
--SELECT #JSON;
declare #url nvarchar(222) = N'https://TestApiEndpoint..net'
declare #authHeader nvarchar(222) = N'Basic tokenadskjfldasjfs'
Declare #Body as varchar(max) = #JSON
EXEC [dbo].[MyAPIPostProc]
#authHeader = #authHeader,
#Body = #JSON,
#url = #url
'''

OUTPUT TO MULTIPLE FILES FROM A SINGLE QUERY

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+'")';

Nested Cursor call is calling inner cursor only once in MYSQL

There are 2 procedures. When tested separately they execute fine.
When first SP calls 2nd SP, this is not called after the first call.
Please help resolve the issue.
First Cursor:
BEGIN
DECLARE vAttendEmpid,vNoOfDays, vempid INT DEFAULT 0;
DECLARE processed BOOLEAN DEFAULT FALSE;
DECLARE curEmp CURSOR FOR Select distinct empid as d1 from rawattendance where DATE_FORMAT( indatetime,'%m') = process_month and DATE_FORMAT( indatetime,'%Y') = process_year order by empid;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET processed = TRUE ;
OPEN curEmp;
loopemp: LOOP
FETCH FROM curEmp INTO vEmpid;
IF processed THEN
CLOSE curEmp;
LEAVE loopemp;
END IF;
--select vEmpid;
CALL sp_attendance(vEmpid,process_month,process_year);
END LOOP loopemp;
END
2nd Cursor.. Nested cursor
BEGIN
DECLARE vInDateTime, vOutDateTime,vTempInDateTime, vTempOutDateTime DATETIME ;
DECLARE vAttendEmpid ,vDiffHr INT DEFAULT 0;
DECLARE eprocessed BOOLEAN DEFAULT FALSE;
DECLARE curAttendance CURSOR FOR Select empid, indatetime ,outdatetime from rawattendance where empid=vEmpid and DATE_FORMAT( indatetime, '%m' ) = process_month and DATE_FORMAT( indatetime, '%Y' ) = process_year
order by indatetime;
OPEN curAttendance;
att_loop:LOOP
FETCH curAttendance INTO vAttendEmpid, vInDateTime,vOutDateTime;
select concat ('In Time 0 ==',vInDateTime, ' out ==', vOutDateTime, ' Empid=',vAttendEmpid);
select 'looping';
IF eprocessed THEN
select 'loop end';
select concat ('In Time 4 ==',vTempInDateTime, ' out ==', vTempOutDateTime, ' Empid=',vAttendEmpid);
SET vDiffHr =TIMESTAMPDIFF(HOUR,vTempInDateTime,vTempOutDateTime);
insert into emp_attendance_processed(empid,in_date_time, out_date_time, workedhr)
values(vAttendEmpid,vTempInDateTime,vTempOutDateTime, vDiffHr);
SET vTempOutDateTime=vOutDateTime;
CLOSE curAttendance;
END IF;
END LOOP att_loop;
END
Try to reset your continue handler variable processed after the inner procedure is called.
SET processed = FALSE;
The Problem is that the HANDLER FOR NOT FOUND is not only executed if the cursor in your first procedure returns no rows, but also if a nested SELECT returns no rows. And as your second procedure contains SELECT statements, I believe one of them is returning an empty set at least one time. If that's not intended, it may have to do with faulty parameters assigned.
OPEN curEmp;
loopemp: LOOP
FETCH FROM curEmp INTO vEmpid;
IF processed THEN
CLOSE curEmp;
LEAVE loopemp;
END IF;
--select vEmpid;
CALL sp_attendance(vEmpid,process_month,process_year);
SET processed = FALSE;
END LOOP loopemp;

DECLARE Error in My-sql Query

I am having query .Which i want to run on a phpmyadmin.
But whenever I run i got error at declare.
I am not able to find out what is the error in this ?
I want to run this block of code as a query from the PHP?
-- Declare a cursor to hold the section information for a specified product
DECLARE section_cursor CURSOR FOR
SELECT DISTINCT cds_especee.sectid, cds_evocee.text, min
(displayorder) displayorder
FROM cds_especee
JOIN cds_evocee ON (cds_especee.sectid = cds_evocee.id)
-- Replace the prodid below with a valid prodid from your data set
WHERE cds_especee.prodid = 'S1522339'
GROUP BY cds_especee.sectid, cds_evocee.text
ORDER BY displayorder ASC
OPEN section_cursor
-- Fetching the first section into variable
FETCH NEXT FROM section_cursor
INTO #section, #sectionname, #order
WHILE ##FETCH_STATUS = 0
BEGIN
-- Print current section to the screen
PRINT '******'+#sectionname+'******'
-- Declare a cursor to hold the header and body information for the
specified product
-- Note that the WHERE statement limits the results to the headers and body falling under the current section
DECLARE espec_cursor CURSOR FOR
SELECT evoc1.text, evoc2.text, displayorder
FROM cds_especee
JOIN cds_evocee evoc1 ON (cds_especee.hdrid = evoc1.id)
JOIN cds_evocee evoc2 ON (cds_especee.bodyid = evoc2.id)
-- Replace the prodid below with a valid prodid from your data set
WHERE cds_especee.prodid = 'S1522339' AND
cds_especee.sectid = #section
ORDER BY displayorder ASC
OPEN espec_cursor
-- Fetching the first header and body into variable
FETCH NEXT FROM espec_cursor
INTO #hdr, #body, #order1
WHILE ##FETCH_STATUS = 0
-- Below is a loop that prints all the headers and bodies for the
current section
BEGIN
PRINT #hdr +': '+#body
FETCH NEXT FROM espec_cursor
INTO #hdr, #body, #order1
END
-- Clear out the espec_cursor as it will be repopulated with data for
the next section as the procedure loops
CLOSE espec_cursor
DEALLOCATE espec_cursor
-- Fetches the next section and returns to the top of the loop
FETCH NEXT FROM section_cursor
INTO #section, #sectionname, #order
PRINT ' '
PRINT ' '
END
-- Clear out the section_cursor as the procedure is over
CLOSE section_cursor
DEALLOCATE section_cursor
Maybe is something about mysql delimiter. Try to run it like this:
DELIMITER $$
-- Declare a cursor to hold the section information for a specified product
DECLARE section_cursor CURSOR FOR
SELECT DISTINCT cds_especee.sectid, cds_evocee.text, min
(displayorder) displayorder
FROM cds_especee
JOIN cds_evocee ON (cds_especee.sectid = cds_evocee.id)
-- Replace the prodid below with a valid prodid from your data set
WHERE cds_especee.prodid = 'S1522339'
GROUP BY cds_especee.sectid, cds_evocee.text
ORDER BY displayorder ASC
OPEN section_cursor
-- Fetching the first section into variable
FETCH NEXT FROM section_cursor
INTO #section, #sectionname, #order
WHILE ##FETCH_STATUS = 0
BEGIN
-- Print current section to the screen
PRINT '******'+#sectionname+'******'
-- Declare a cursor to hold the header and body information for the
specified product
-- Note that the WHERE statement limits the results to the headers and body falling under the current section
DECLARE espec_cursor CURSOR FOR
SELECT evoc1.text, evoc2.text, displayorder
FROM cds_especee
JOIN cds_evocee evoc1 ON (cds_especee.hdrid = evoc1.id)
JOIN cds_evocee evoc2 ON (cds_especee.bodyid = evoc2.id)
-- Replace the prodid below with a valid prodid from your data set
WHERE cds_especee.prodid = 'S1522339' AND
cds_especee.sectid = #section
ORDER BY displayorder ASC
OPEN espec_cursor
-- Fetching the first header and body into variable
FETCH NEXT FROM espec_cursor
INTO #hdr, #body, #order1
WHILE ##FETCH_STATUS = 0
-- Below is a loop that prints all the headers and bodies for the
current section
BEGIN
PRINT #hdr +': '+#body
FETCH NEXT FROM espec_cursor
INTO #hdr, #body, #order1
END
-- Clear out the espec_cursor as it will be repopulated with data for
the next section as the procedure loops
CLOSE espec_cursor
DEALLOCATE espec_cursor
-- Fetches the next section and returns to the top of the loop
FETCH NEXT FROM section_cursor
INTO #section, #sectionname, #order
PRINT ' '
PRINT ' '
END
-- Clear out the section_cursor as the procedure is over
CLOSE section_cursor
DEALLOCATE section_cursor$$
DELIMITER ;
You cannot use many of those statements including DECLARE, OPEN, FETCH, CLOSE in a simple MySQL script. You should create a source object for this purpose. For example you could do it using stored procedure. There is a good example in the documentation - Cursors.
Also PRINT is not MySQL statement.

cursor logic in ssis

i have been strugling to convert the following t sql task into an automated ssis package.
i tried implementing using for loop conntainer but while creating the looping logic i am stucking off. i really appreciate of some one could help me out with logic
here is the t- sql code
-- SCRIPT TO BULK IMPORT MATERNAL HLA & INSERT CORD NIMA
IF OBJECT_ID('tempdb..#maternal_hla_from_solar') IS NOT NULL
BEGIN
drop table #maternal_hla_from_solar
END
CREATE TABLE #maternal_hla_from_solar(
[donor_id] [int] NOT NULL,
[antigen_id] [int] NOT NULL
)
-- bulk upload maternal HLA from file
BULK
INSERT #maternal_hla_from_solar
FROM 'C:\Users\zabeenp\Documents\SQL\populate_db\data\20111212_maternal_hla.txt'
WITH
(
FIRSTROW = 2,
MAXERRORS = 0,
FIELDTERMINATOR = '\t',
ROWTERMINATOR = '\n'
)
-- declare variables
DECLARE #donor_id int
DECLARE #maternal_hla varchar(5000)
DECLARE #definitive_type_date date = GETDATE()
DECLARE #modified_on datetime2(7) = GETDATE()
-- Cursor to process each row from #maternal_hla_from_solar
DECLARE c_insertCordNima CURSOR FAST_FORWARD
FOR select DISTINCT donor_id from #maternal_hla_from_solar -- important to use DISTINCT here
OPEN c_insertCordNima
FETCH NEXT FROM c_insertCordNima INTO #donor_id
WHILE ##FETCH_STATUS = 0
BEGIN
SET #maternal_hla = '' -- important to wipe string each time
-- concatenare maternal antigen_ids into one string
SELECT #maternal_hla = COALESCE(#maternal_hla + ',', '') + CONVERT(VARCHAR(10),antigen_id)
FROM #maternal_hla_from_solar
where donor_id = #donor_id
-- remove first comma
SET #maternal_hla = (select right(#maternal_hla,len(#maternal_hla)-1))
-- exec insertCordNIMA SP
EXECUTE insertCordNIMA
#donor_id
,#maternal_hla
,#definitive_type_date
,#modified_on
FETCH NEXT FROM c_insertCordNima INTO #donor_id
END
CLOSE c_insertCordNima
DEALLOCATE c_insertCordNima
maybe try to rewrite the cursor using a Recursive CTE?
http://msdn.microsoft.com/en-us/library/ms186243.aspx