sql server assign declared variable to a column name - sql-server-2008

Is there a way to do the following?
declare #start_date int
declare #end_date int
set #start_date = 202003
set #end_date = 202004
select
'Total_Units' as Metric_Description
,cast(count(*) as varchar(max)) as #end_date
from table
I am trying to use the #end_date as the name of a column in a query result, in other words, I am trying to do this without having the change the 202004 in all the multiple queries each month
select
'Total_Units' as Metric_Description
,cast(count(*) as varchar(max)) as '202004'
from table

This should help you
declare #start_date int
declare #end_date varchar(20)
set #start_date = 202003
set #end_date = '202004'
declare #query varchar(max)
set #query = 'select
''Total_Units'' as Metric_Description
,cast(count(*) as varchar(max)) as [' + #end_date + ']
from table'
exec sp_sqlexec #query

Related

How can i concat the values in MySql?

Please find the below code, The below code is sql server code[Stored Procedure] i am converting sql to mysql in this link mysql and below is the sql SP
USE databasename
GO
ALTER PROCEDURE GetSbsberIDbyDept
#P_DepartmentIds varchar(max),
#OP_ID varchar(max) output
AS
BEGIN
Declare #Position int
Declare #length int
Declare #value varchar(8000)
Declare #SubscribrIDs varchar(max)
Declare #FinalSubscriberids varchar(max) = ''
SET #Position = 0
SET #length = 0
select #P_DepartmentIds
WHILE CHARINDEX(',', #P_DepartmentIds, #Position+1)>0
BEGIN
set #Length = CHARINDEX(',', #P_DepartmentIds, #Position+1) - #Position
set #value = SUBSTRING(#P_DepartmentIds, #Position, #length)
select #SubscribrIDs = STUFF((SELECT ', ' + cast(SubscriberId as varchar(max)) from SbsberDetails
where Deptid = #value and ParentId is null order by SubscriberId asc FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)') ,1,2,'')
if(#SubscribrIDs is not null)
begin
set #FinalSubscriberids += cast(#SubscribrIDs as varchar(max)) + ',';
end
set #Position = CHARINDEX(',', #P_DepartmentIds, #Position + #length) +1
END
SET #OP_ID = #FinalSubscriberids
END
And i converted to MySql but i am getting the error in STUFF statement like STUFF is not valid input at this position, below is the Mysql code
USE databasename
DELIMITER //
CREATE PROCEDURE GetSbsberIDbyDept(
p_P_DepartmentIds longtext,
p_OP_ID out longtext )
BEGIN
Declare v_Position int;
Declare v_length int;
Declare v_value varchar(8000);
Declare v_SubscribrIDs longtext;
Declare v_FinalSubscriberids longtext Default '';
SET v_Position = 0;
SET v_length = 0;
select p_P_DepartmentIds
WHILE; CHARINDEX(',', p_P_DepartmentIds, v_Position+1)>0
BEGIN
set v_length = CHARINDEX(',', p_P_DepartmentIds, v_Position+1) - v_Position;
set v_value = SUBSTRING(p_P_DepartmentIds, v_Position, v_length);
set v_SubscribrIDs = STUFF((SELECT Concat(', ' , cast(SubscriberId as longtext)) from SbsberDetails
where Deptid = v_value and ParentId is null order by SubscriberId asc FOR XML; PATH(''), TYPE).value('.', 'NVARCHAR(MAX)') ,1,2,'')
if(v_SubscribrIDs is not null)
then
set v_FinalSubscriberids += concat(cast(v_SubscribrIDs as longtext) , ',');
end if;
set v_Position = CHARINDEX(',', p_P_DepartmentIds, v_Position + v_length) +1;
END;
SET p_OP_ID = v_FinalSubscriberids;
END;
//
DELIMITER ;
How do i convert the above sql code to MySql?
STUFF is SQL server function so it's thrown error in mysql, The thing that i got your are trying to row concat but in mysql there is funtion name GROUP_CONCAT for group cancating ,so you can use it instead of stuff

Clear handler before function return value to procedure mysql

I have the mysql version 5.5.38.
When I call a procedure that call a function inside there, handler condition its activated into function and raise up to procedure. I need that handler condition on function not affect the process on procedure. Included the function and procedure.
function:
DELIMITER $$
CREATE FUNCTION FUNCTION_HOURLY_GAS_CHANGE(INI_DATE DATETIME, TANK INT)
RETURNS INT
NOT DETERMINISTIC
BEGIN
DECLARE END_GAL INT;
DECLARE CONTINUE HANDLER FOR SQLEXCEPTION SET END_GAL = -1;
SET END_GAL = 0;
SELECT GALLONS INTO END_GAL
FROM TLS_TEMP_DATA WHERE FK_TANK = TANK
AND DATE LIKE CONCAT(DATE_FORMAT(DATE_ADD(DATE_FORMAT(INI_DATE, '%Y-%m-%d %H'), INTERVAL 1 HOUR), '%Y-%m-%d %H'),':%')
AND REQUEST_TYPE = 1;
RETURN END_GAL;
END $$
DELIMITER ;
procedure:
DELIMITER $$
CREATE PROCEDURE HOURLY_GAS_CHANGE(IN dateReport char(50), IN tank INT)
BEGIN
DECLARE COMPLETELOOP INT DEFAULT 0;
DECLARE INI_DATE DATETIME;
DECLARE INI_GAL INT;
DECLARE END_GAL INT;
DECLARE DIFF INT;
DECLARE V_HOUR CHAR(50);
DECLARE V_INI_GAL CHAR(50);
DECLARE V_END_GAL CHAR(50);
DECLARE V_DIFF CHAR(50);
DECLARE INITIALDATA CURSOR FOR
SELECT
DATE, GALLONS FROM TLS_TEMP_DATA WHERE FK_TANK = tank
AND (DATE BETWEEN CONCAT(dateReport, ' 00:00:00') AND CONCAT(dateReport, ' 23:59:59')) AND REQUEST_TYPE = 1
ORDER BY ID;
DECLARE CONTINUE HANDLER FOR SQLSTATE '02000' SET COMPLETELOOP = 1;
DROP TEMPORARY TABLE IF EXISTS HOURLYGASCHANGE;
CREATE TEMPORARY TABLE HOURLYGASCHANGE(
`HOUR_DATA` CHAR(50) NOT NULL,
`INI_GAL` CHAR(50) NOT NULL,
`END_GAL` CHAR(50) NOT NULL,
`DIFF` CHAR(50) NOT NULL)
ENGINE=MEMORY;
OPEN INITIALDATA;
READ_LOOP: LOOP
FETCH INITIALDATA INTO INI_DATE, INI_GAL;
IF COMPLETELOOP THEN
LEAVE READ_LOOP;
END IF;
SET END_GAL = 1;
SET END_GAL = FUNCTION_HOURLY_GAS_CHANGE(INI_DATE, tank);
IF END_GAL > 0 THEN
SET DIFF = (END_GAL - INI_GAL);
SET V_DIFF = CAST(DIFF AS CHAR(50));
SET V_END_GAL = CAST(END_GAL AS CHAR(50));
ELSE
SET V_DIFF = 'N/A';
SET V_END_GAL = 'NOT UPDATED';
END IF;
SET V_INI_GAL = CAST(INI_GAL AS CHAR(50));
SET V_HOUR = CAST(DATE_FORMAT(INI_DATE, '%H') AS CHAR(50));
INSERT INTO HOURLYGASCHANGE VALUES(V_HOUR, V_INI_GAL, V_END_GAL, V_DIFF);
END LOOP;
close INITIALDATA;
SELECT * FROM HOURLYGASCHANGE;
END $$
DELIMITER ;
I can't fix the problem, but I found a solution to replace the function, I capture empty result into IFNULL function and now I can set a specific value when select show me a empty result.
SELECT (
IFNULL(
(
SELECT ENDTLS.GALLONS
FROM TLS_TEMP_DATA ENDTLS
WHERE ENDTLS.FK_TANK = tank
AND ENDTLS.DATE LIKE ONCAT(DATE_FORMAT(DATE_ADD(DATE_FORMAT(INI_DATE, '%Y-%m-%d %H'), INTERVAL 1 HOUR), '%Y-%m-%d %H'),':%')
AND ENDTLS.REQUEST_TYPE = 1
)
, -1)
) INTO END_GAL;

Unknown Column in NEW

DELIMITER $$
CREATE TRIGGER `InitialCuring_update` BEFORE UPDATE ON `specimen_register`
FOR EACH ROW BEGIN
DECLARE DateOFJob1 Date;
DECLARE SampleTime1 varchar(50);
DECLARE Curing_LCDate1 varchar(50);
DECLARE Curing_LCTime1 varchar(50);
DECLARE DT1 DATETIME;
DECLARE DT2 DATETIME;
DECLARE ReportD Date;
SELECT `DateOfJob`,`Sample_Time`,`Curing_LCDate`,`Curing_LCTime`,`ReportDue`
INTO DateOFJob1,SampleTime1,Curing_LCDate1,Curing_LCTime1,ReportD
FROM job_register j, test_register t
WHERE j.JID = t.ParentID
AND t.fts = NEW.FTS;
SET DT1 = STR_TO_DATE(CONCAT(DateOFJob1, ' ', SampleTime1), '%Y-%m-%d %H%i');
SET DT2 = STR_TO_DATE(CONCAT(Curing_LCDate1, ' ', Curing_LCTime1), '%Y-%m-%d %H%i');
SET NEW.Initial_Cure = time_format(timediff(DT2,DT1),'%H');
SET NEW.Due_Date = DATE_ADD(DateOFJob1,INTERVAL NEW.Age DAY);
IF (NEW.Due_Date > ReportD) THEN
SET NEW.ReportDue = NEW.Due_Date;
END IF;
END $$
DELIMITER ;
Returns Error
#1054 - Unknown column 'ReportDue' in 'NEW'
ReportDue is in the job_register table, I've tried all manner of things and i cant seem to fix this.
I've tried using job_register.ReportDue and the alias j but it just dosen't work.

MySql Procedure for randomly populating rows only populates one row

I have a procedure that populates randomly records in a table.
But when i execute that procedure, the procedure inserts only one row.
CAN ANYONE HELP!
create procedure aa
( #row INT
)
as
begin
declare #numint as int
declare #string as VARCHAR(10)
declare #length as INT
declare #code as INT
declare #oid as uniqueidentifier
set #numint =0;
WHILE #numint <= #row
BEGIN
SET #numint = #numint + 1;
set #oid = newid();
SET #length = ROUND(10*RAND(),0);
SET #string = '';
WHILE #length > 0 BEGIN
SET #length = #length-1;
SET #code = ROUND(10*RAND(),0) - 1;
IF #code BETWEEN 1 AND 26
SET #string = #string + CHAR(ASCII('a')+#code-1);
ELSE
SET #string = #string + ' ';
END
end
-- Ready for the record
SET NOCOUNT ON;
INSERT INTO test_table VALUES (
#oid,
#numint,
ROUND(2000000*RAND()-1000000,2),
CONVERT(DATETIME, ROUND(50000*RAND()-10000,2)),
#string
)
END
exec procedure '10'
Your insert statement is outside of the loop. Move it up to be inside the first loop and you should get the correct number of rows.

Issue with executing SQL Procedure

I have an issue executing below piece of code:
DECLARE #CUTOFFDAYS_i INT
DECLARE #SQL NVARCHAR(MAX)
DECLARE #SQL1 NVARCHAR(MAX)
SET #CUTOFFDAYS_i = 750
CREATE TABLE #TMP(
EMPID INT,
EMPNAME VARCHAR(35)
)
SET #SQL = 'SELECT EMPID, EMPNAME INTO #TMP FROM EMPDB..EMPTABLE
WHERE DATEDIFF(DAY, CREATEDDATE, GETDATE()) > #CUTOFFDAYS_i
AND ERRORMESSAGE = '''''
SET #SQL1 = 'SELECT * FROM #TMP'
EXEC SP_EXECUTESQL #SQL
EXEC SP_EXECUTESQL #SQL1
Even then I don't get any result upon
SELECT * FROM #TMP
Your usage of # is wrong. #TMP is a temporary table that's only availble to the connection that makes it. I think what you're looking for is ##TMP.
But if you need such a temporary table, I would advice you to make a proper table instead as it's much easier to manage and keep track off and keeps less strain on your tempdb.
First of all you should declare #SQL and #SQL1 as a fixed maximum length varchar not exceeded 8000 (I guess it's not the restriction for the current MS SQL version???):
DECLARE #SQL NVARCHAR(1000)
DECLARE #SQL1 NVARCHAR(1000)
Then you shouldn't use () when call SP_EXECUTESQL
EXEC SP_EXECUTESQL #SQL
EXEC SP_EXECUTESQL #SQL1
And the finally you should use global temp table ##TMP in SP_EXECUTESQL for INSERT and then SELECT or you should declare local #Tmp table before the first SP_EXECUTESQL call
DECLARE #CUTOFFDAYS_i INT
DECLARE #SQL NVARCHAR(1000)
DECLARE #SQL1 NVARCHAR(1000)
SET #CUTOFFDAYS_i = 750
SET #SQL = 'SELECT EMPID, EMPNAME INTO ##TMP FROM EMPDB..EMPTABLE
WHERE DATEDIFF(DAY, CREATEDDATE, GETDATE()) > #CUTOFFDAYS_i
AND ERRORMESSAGE = '''''
SET #SQL1 = 'SELECT * FROM ##TMP'
EXEC SP_EXECUTESQL #SQL
EXEC SP_EXECUTESQL #SQL1