Using Arrays in SQL - mysql

I have this sql statement:
DECLARE #option_id INT;
SELECT DISTINCT product_options.option_id
INTO #option_id
FROM product_options,
product_options_descriptions
WHERE product_options.product_id = '31288'
AND product_options_descriptions.option_name = "Color";
SELECT #option_id;
Which works fine. What I would like to do is is use #option_id to select multiple ids into an array. However as far as I can tell DECLARE #var only works with single values and I can't find any information on array datatypes in sql.
In outline I want to do the following
declare #option_id;
SELECT #option_id;
DECLARE #id_array;
SELECT into #id_array WHERE id = #option_id;
DECLARE #return_array;
FOREACH #id IN #id_array {
#return_array[] = SELECT value FROM column where id = #id
}
SELECT #return_array
Does anyone know where I can find tutorials ect to achieve this?

You can use temporary table , table prefixed with #
CREATE TABLE #YourTable (
YourColumn int
)
LInk : http://www.sqlteam.com/article/temporary-tables
For mysql syntax : http://dev.mysql.com/doc/refman/5.1/en/create-table.html

Related

HANA SQL Select Count (*) from multiple tables found in a table

DECLARE VI_CNT INTEGER DEFAULT 0;
DECLARE VI_IDX INTEGER;
DECLARE VI_LIMIT INTEGER;
DECLARE VS_OUTPUTSTRG1 NVARCHAR(500);
DECLARE VS_OUTPUTSTRG2 NVARCHAR(500);
/* ANAGRAFICA TABELLE FLUSSI */
ANAGRAFICA = SELECT *
FROM (SELECT DISTINCT
ZCSOURSYS,
ZTABLE,
ROW_NUMBER() OVER (ORDER BY ZCSOURSYS) AS ROW_NB
FROM ZDAFNE_INFO);
/************ FOR ***********/
SELECT COUNT (ZTABLE) INTO VI_LIMIT FROM :ANAGRAFICA;
FOR VI_IDX IN 1..:VI_LIMIT DO
VI_CNT = :VI_IDX;
SELECT ZTABLE INTO VS_OUTPUTSTRG1 FROM :ANAGRAFICA WHERE ROW_NB = VI_IDX;
END FOR;
VS_OUTPUTSTRG2 := 'INSERT INTO "TEAMBW"."IFRS17.INTEGRATION.DATA_QUALITY::ZTB_DQ_DAFNE_TEST" SELECT COUNT(*) FROM '||:VS_OUTPUTSTRG1||'';
EXECUTE IMMEDIATE (:VS_OUTPUTSTRG2);
Hello everyone! Thanks in advance!
Any help about this? The output doesn't insert anything... maybe I'm doing something wrong?
It looks like the OP wants to store the raw record count of a list of tables into yet another table.
This requirement can be met without the use of SQLScript.
SAP HANA keeps the number of committed records in tables available in catalog tables like [M_TABLES][1].
With this information available, the INSERT-statement can be rewritten like so:
INSERT INTO
"TEAMBW"."IFRS17.INTEGRATION.DATA_QUALITY::ZTB_DQ_DAFNE_TEST"
(TABLE_NAME, RECORD_COUNT)
(SELECT
TABLE_NAME, RECORD_COUNT
FROM M_TABLES
WHERE
SCHEMA_NAME ='xyz'
AND TABLE_NAME IN (SELECT DISTINCT TABLE_NAME
FROM ZDAFNE_INFO)
);
This solution works as long as no filtering of to-be-counted records in the source tables is required.

MySQL procedure with query string

I am a newbie to using query strings in mysql and I have tried to write this procedure to drop tables under certain conditions. I don't reall know what I'm doing wrong and need help with getting the procedure to work or for someone to point me in the right direction. Thanks.
BEGIN
DECLARE String scheduler = 'select status from mysql.scheduler where id=0' ;
DECLARE String auftragpos = 'SELECT count("SchemaName") FROM "SYS.Tables" where "SchemaName" = dwh and "Name" = lexware_fk_auftragpos';
DECLARE String auftrag = 'SELECT count("SchemaName") FROM "SYS.Tables" where "SchemaName" = dwh and "Name" = lexware_fk_auftrag';
IF(auftragpos > 1)
BEGIN
drop table "dwh.lexware_fk_auftragpos";
END
IF(auftrag > 1)
BEGIN
drop table "dwh.lexware_fk_auftrag";
END
END
The syntax for declaring a variable is
DECLARE variablename datatype;
So it should be
DECLARE auftragpos INT;
Then you need to assign the result of the query to the variable. You do that by putting the SELECT query in parentheses.
You also should not quote table names, and you need to quote the literal strings you're using for the schema and table names you're searching for.
SET auftragpos = (
SELECT count(*)
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = 'dwh' AND TABLE_NAME = 'lexware_fk_auftragpos');
But there's really no need to do this. If you want to prevent an error from DROP TABLE, just add the IF EXISTS option.
DROP TABLE IF EXISTS dwh.lexware_fk_auftragpos;

SQLserver Store Column as variable and loop through it

I am still pretty new to SQL server and I am not sure how to do this. I am first creating a table with just the IDs I need:
SELECT DISTINCT
ID_NUMBER
INTO
#IDlist
FROM
V_Rpt_IDs WITH (NOLOCK)
WHERE
ID_NUMBER in (
'1000764169'
,'1005870537'
,'1008053856'
,'1008054376'
,'1008410224'
,'1008411317'
,'1008465318'
,'1008466074'
,'1008492967'
,'1010546872'
,'1010554301')
Select * from #IDlist
And this works fine. But now I would like to declare a variable to represent this column, or each item in this column, so that I can then do a loop where it loops through each ID Number and returns information about each one and then presents all of that as a table. Here is my shot at that:
Declare #IDNumber as VARCHAR(10)
Set #IDNumber = #IDlist.ID_NUMBER
DECLARE #cnt INT = 0
WHILE #cnt < (Select Count(*) From #IDlist)
BEGIN
SELECT TOP 1
NAME
,MAILING_ADDRESS_1
,MAILING_ADDRESS_CITY
,MAILING_STATE
,MAILING_ZIP
from
V_Rpt_Info
WHERE
ID_NUMBER = #IDNumber
SET #cnt = #cnt + 1
END
DROP TABLE #IDlist
But when I Set the #IDNumber variable to #IDlist.ID_NUMBER, it says The multi-part identifier "#IDlist.ID_NUMBER" could not be bound.
How do I do this?
Thanks
The way you set the variable is not correct, SQL doesn't know which ID_NUMBER row it should assign to the #IDNumber variable.
You should do this with a SELECT, for example
SET #IDNumber = SELECT TOP 1 ID_NUMBER FROM #IDlist
But, why would you like to loop through this temporary table this way ? Isn't it possible to join the necessary data with this table instead of doing it one by one ?
Rather then loop through, you're going to want to join your ID table to your V_Rpt_Info view.
SELECT
NAME
, MAILING_ADDRESS_1
, MAILING_ADDRESS_CITY
, MAILING_STATE
, MAILING_ZIP
FROM V_Rpt_Info V
INNER JOIN #IDlist ID
ON V.ID_NUMBER = ID.ID_NUMBER

Loop through table variable and insert missing rows into new table variable

I have a table variable which is populated with a number of rows. What I am trying to achieve, is to loop through each row of the table variable, see if the ID column exists in another standard table and add that row to a newly created table variable.
My code is as follows:
DECLARE
#Intervention_ID int
SET #Intervention_ID = 969
/*---Check if intervention has pre-requisites---*/
DECLARE #PreRequisites TABLE
(
[Intervention_ID] int
)
INSERT INTO #PreRequisites
(
[Intervention_ID]
)
SELECT IP.[Requisite_ID]
FROM DI_Intervention_Prerequisites IP
WHERE
IP.[Intervention_ID] = #Intervention_ID
AND IP.[Prerequisite] = 1
/*---Check if pre-requisites have been completed---*/
DECLARE #Result TABLE
(
[Type_ID] int
, [Type_Name] nvarchar(max)
, [Intervention_ID] int
, [Intervention_Name] nvarchar(max)
)
WHILE NOT EXISTS
(
SELECT TOP 1 1
FROM DI_Employee_Intervention EI
WHERE
EI.[Intervention_ID] = (SELECT [Intervention_ID] FROM #PreRequisites)
)
INSERT INTO #Result
(
[Type_ID]
, [Type_Name]
, [Intervention_ID]
, [Intervention_Name]
)
As you can see, I am stuck at the WHILE NOT EXISTS part of the code. What needs to happen is for each row within #PreRequisites that does not exist in DI_Employee_Intervention, that specific #PreRequisites row need to be inserted into #Result.
Why don't you just use a set-based approach instead of the RBAR (row-by-agonizing-row) procedural approach you have now??
Something like:
INSERT INTO #Result([Type_ID], [Type_Name], [Intervention_ID], [Intervention_Name])
SELECT
... (some columns to match the columns of #Result)......
FROM
dbo.DI_Intervention_Prerequisites IP
WHERE
IP.[Intervention_ID] = #Intervention_ID
AND IP.[Prerequisite] = 1
AND NOT EXISTS (SELECT *
FROM DI_Employee_Intervention EI
WHERE EI.[Intervention_ID] = IP.[Intervention_ID] )
or something like that (I didn't quite understand all your intermediate steps and why you take them....)

Specifying SQL variable to xquery exist method to check if value is in given set of values

I am trying to query an XML column to return all rows where an attribute is in a list of possible values.
XQuery allows something like
SELECT COUNT(*)
FROM table
WHERE xml_col.exist('//Field.[#name=("value1","value2","value3")]') = 1
which would return the number of records that have a Field with attribute #name set to either "value1", "value2" or "value3".
What I'd like to do is write a concise query that could handle the set "value1", "value2", "value3" as an input parameter, e.g.
DECLARE #list NVARCHAR(100)
SET #list = '("value1","value2","value3")'
SELECT COUNT(*)
FROM table
WHERE xml_col.exist('//Field.[#name=sql:variable("#list")]') = 1
which, of course, is invalid. Any suggestions would be appreciated!
simplest way to do it is (if your name could not contain ,):
declare #list nvarchar(max) = ',value1,value2,value3,'
select count(*)
from test
where xml_col.exist('//Field[contains(sql:variable("#list"), concat(",", #name, ","))]') = 1;
or SQL way:
select count(*)
from test
where
exists
(
select 1 from xml_col.nodes('//Field') as T(C)
where T.C.value('#name', 'nvarchar(max)') in ('value1', 'value2', 'value3')
)
sql fiddle demo
Maybe in this case it would be easier to check on the SQL side:
SELECT COUNT(*)
FROM table
WHERE xml_col.value('(//Field/#name)[1]', 'nvarchar(255)') in ('value1', 'value2', 'value3')
At least this would work if there is only one Field element in your XML, otherwise it would get a bit more complex.
You may try following construct:
select count(1)
from [table] t
where exists (
select 1 from (values ('value1'),('value2'),('value3')) l(v)
where t.xml_col.exist('//Field[#name=sql:column("l.v")]') = 1);
Also it can be used with table variable or table valued parameter in the following way:
declare #list table (value varchar(100))
insert into #list values ('value1'),('value2'),('value3')
or
create type ListOfValues as table (value varchar(100))
GO
declare #list ListOfValues
insert into #list values ('value1'),('value2'),('value3')
and then
select count(1)
from [table] t
where exists(select 1 from #list l
where t.xml_col.exist('//Field[#name=sql:column("l.value")]') = 1);