Select from hundreds of tables at once (.mdb) - sql

We have .mdb file with hundreds of tables: Lesson1, Lesson2, Lesson3, Lesson4, etc. All tables have the same structure:
Lesson<n>
----------------
slide_id
name
description
status
created_date
created_by
updated_date
updated_by
What SQL statement would generate a result like this:
| table_name | slide_id | name |
|-----------------------|-------------------------------|
| Lesson1 | 1 | name for slide 1 of lesson 1 |
| Lesson1 | 2 | name for slide 2 of lesson 1 |
| Lesson2 | 1 | name for slide 1 of lesson 2 |
| Lesson2 | 2 | whatever |
| Lesson2 | 3 | again whatever |
etc.
So there are a few points here:
table names must be included
there are hundreds of tables

If the table names are known, you can create a query like:
SELECT 'Lesson1' AS table_name, slide_id, name, ... FROM Lesson1
UNION ALL SELECT 'Lesson2', slide_id, name, ... FROM Lesson2
UNION ALL SELECT 'Lesson3', slide_id, name, ... FROM Lesson3
UNION ALL SELECT 'Lesson4', slide_id, name, ... FROM Lesson4
UNION ALL SELECT 'Lesson5', slide_id, name, ... FROM Lesson5
Cursors are only needed if the number of tables is in constant flux. If not, this should do the trick.
Hint: to generate the initial query, paste the names of the table in Excel, and use a formula in the next cell over to create that table's "UNION ALL" statement. Then copy and paste straight back into Access. (Or create it dynamically using a cursor, but copy/paste and a quick formula is easy, and you can save the excel file just in case you need to add tables in bulk, change the columns selected, etc.)
And, obviously, the end solution should be to consolidate the tables, if possible, and add a discriminator field when querying. Heck, if you have to, it's easier to maintain hundreds of queries that each pull one lesson's rows (again, Excel can be a handy batch-update tool), than hundreds of lessons tables that must have identical structures.

Using sql server, I can unfortunately see this only done with a CURSOR X-(.
This should help
DECLARE #Name VARCHAR(50)
DECLARE Cur CURSOR FOR
SELECT name
FROM sysobjects
WHERE xtype = 'U'
and name like 'Lesson%'
OPEN Cur
FETCH NEXT FROM Cur INTO #Name
DECLARE #RetTable TABLE(
TableName VARCHAR(50),
slide_id INT,
name VARCHAR(100)
)
WHILE ##FETCH_STATUS = 0
BEGIN
INSERT INTO #RetTable EXEC ('SELECT ''' + #Name + ''',slide_id , Name FROM ' + #Name)
FETCH NEXT FROM Cur INTO #Name
END
CLOSE Cur
DEALLOCATE Cur
SELECT *
FROm #RetTable
OK, then if you can use a macro/vba code you can create a temp table called AllLessons and run the following code. I tested this from a form with a button.
Private Sub Command0_Click()
Dim iTable As Integer
For iTable = 0 To CurrentDb.TableDefs.Count - 1
Dim tableName As String
tableName = CurrentDb.TableDefs(iTable).Name
If (Left(tableName, Len("Lesson")) = "Lesson") Then
CurrentDb.Execute "INSERT INTO AllLessons ([table_name],[slide_id],[name]) SELECT """ & tableName & """, [slide_id],[name] FROM " & tableName
End If
Next iTable
End Sub

Related

SQL calculated field based of data in another table

I have two tables, Engineering table and Instrumentation table. In the Engineering table I have the columns and possible data below:
Tag | Speed Control
PC-1234 |
ME-1235 |
BF-1236 |
In the Instrumentation Table I have the following columns and data
Function | Tag
SC | 1234
SC | 1235
SC | 1237
I want to automate the Speed Control column in the Engineering table to say Yes or No IF there is a line of data in the Instrumentation table with the function as SC and the Tag column have matching data with the number part of the Tag column in the Engineering table. So the results would like like the below:
Tag | Speed Control
PC-1234 | Yes
ME-1235 | Yes
BF-1236 | No
Please help with the best way to do this. Thanks in advance for any help.
You don't want a separate column in the Engineering table for this. You just need a view which you can query
CREATE VIEW EngineeringSpeedControl
AS
SELECT
e.Tag,
SpeedControl = CASE WHEN i.Tag IS NULL THEN 'No' ELSE 'Yes' END
FROM dbo.Engineering e
LEFT JOIN dbo.Instrumentation i
ON i.Tag = RIGHT(e.Tag, LEN(e.Tag) - 3)
AND i.[Function] = 'SC';
Unfortunately, due to the poor design of the tables, you need to muck around with string manipulation.
Ideally you would have the Engineering.Tag column split into separate parts, so you could just do a straight join
LEFT JOIN dbo.Instrumentation i
ON i.Tag = e.Tag
AND i.[Function] = 'SC';
as i don't know if the Tag column in engineers is always of the same format, i keep my query so that it can have similar design xxxxx-nnnnnnnnn with a minus between.
UPDATE [dbo].[Engineering]
SET [Speed Control] =
CASE WHEN EXISTS ( SELECT 1 FROM [dbo].[Instrumentation] i WHERE RIGHT([dbo].[Engineering] .[tag],CHARINDEX('-', (REVERSE([dbo].[Engineering] .[tag]))) - 1) = CAST(i.[Tag] AS VARCHAR(10))) then 'YES' ELSE 'NO' END
WHERE [Speed Control] IS NULL
result will be
Create a function and use a function in calculated columns
create table instrumentation([Function] varchar(200) null, Tag varchar(200) null)
insert into instrumentation values('SC', '1234'),('SC', '1235'),('SC', '1237')
create Function fn_Speed (#tag varchar(200))
returns varchar(200)
as
begin
declare #tagg varchar(200)= (select SUBSTRING(#tag, charindex('-', #tag)+1,10))
declare #result varchar(200)
--return #tagg
If exists (
select 1 from instrumentation where tag =#tagg)
select #result= 'True'
else
select #result= 'False'
return #result
end
Create table engineering (tag varchar(200), Speed as dbo.fn_Speed (tag) )
insert into engineering(tag)values('PC-1234'), ('ME-1235'), ('BF-1236')

check & validate table containing similar values

I have this table called businessname (id, name) and I need to insert data into this table but before that I need to check for similar name is existing in the table. this table called similarwords display below.
id | words
===============================
1 | transport, travel
-------------------------------
2 | IT, information technology
-------------------------------
3 | builders, contractors
-------------------------------
As example-> If there is business name called "ABCD transport" when user try to insert "ABCD travel" it should validate & give error message "Similar name already exists." is there way to do this in SQL ?
You can try a procedure like this to insert data -
CREATE PROCEDURE DATA_INSERT (#ID INT, #NAME VARCHAR(100))
AS BEGIN
IF EXISTS (SELECT * FROM BUSINESSMAN WHERE NAME = #NAME)
BEGIN
PRINT ('Similar name already exists')
END
ELSE
BEGIN
INSERT INTO BUSINESSMAN VALUES (#ID, #NAME)
END
END
EXEC DATA_INSERT 4,'ABCD TRANSPORT'
Although I will suggest you to create an primary key on that column if you doesn't want duplicates to be inserted.

How to handle an array in a stored procedure on DB2?

I'm developing an app which store data in DB2, and I should be able to 'delete' data in bulk in a table of a DB. Actually the way to 'delete' the data is by changing its 'deleted' value to 'Y'.
The form of the table is:
id | name | deleted |
1 | name1 | N |
2 | name2 | N |
...
x | namex | N |
What I want to do is to make a SQL stored procedure which take as a parameter one array with the IDs of the items I need to change from 'N' to 'Y'.
The way I do it (individually) is:
UPDATE MyTable DELETED = 'Y' where id = '1';
So with an stored procedure I should only send the array with this form:
[1, 20, 5, ... , x]
and the rows with those Id should be changed to Y.
The structure for the stored procedure I was thinking about is:
PROCEDURE deleteSeveral (arrayWithIds)
LANGUAGE SQL
BEGIN
-- loop for ids array
UPDATE MyTable DELETED = 'Y' where id = arrayWithIds[i];
-- Ciclo para recorrer el arreglo
END
Could anybody help me with this? Thanks!
Try to pass the list of IDs as an "xml-like" string:
UPDATE MyTable t
SET DELETED = 'Y'
where exists (
select 1
from xmltable (
'$D/d/i' passing xmlparse(document '<d><i>1</i><i>20</i><i>5</i></d>') as "D"
columns
i int path '.'
) p
where p.i=t.id
)

Sybase ASE 15 Aggregate Function for strings

I'am findind a way to aggregate strings from differents rows into a single row in sybase ASE 15. Like this:
id | Name Result: id | Names
-- - ---- -- - -----
1 | Matt 1 | Matt, Rocks
1 | Rocks 2 | Stylus
2 | Stylus
Something like FOR XML PATH in T-SQL.
Thanks!
Sybase ASE does not have any string aggregate functions like list() or group_concat(); and while there is some support for FOR XML, it does not include support for the PATH option/feature.
Assuming you could have an unknown/variable number of rows to append, your only (ASE 15) T-SQL option would be a cursor-based solution.
If you find yourself working with ASE 16 you could write a user-defined function (UDF) to accomplish the task, eg: emulate group_concat() in ASE 16
Write below query :-
select id, cursorfunc(id) from table
Then create below cursor which is used in above query
DECLARE ListCurs CURSOR FOR
//Query to fetch the name
select name from table where id=#id
OPEN ListCurs
SELECT #Status = 0
WHILE #Status = 0
BEGIN
FETCH ListCurs INTO #name
IF #Status = 0
BEGIN
SELECT #res = CASE WHEN #res IS NULL THEN '' ELSE #res + '& ' END + #name
END
END
CLOSE ListCurs
RETURN (#res)
You could try this:
select id,list(Names,',' order by id) from TableName a group by id

how to build a Comma seperated list from a table in SQL CE?

how to build a Comma seperated list from a table in SQL CE ?
I have table named Group and it has two columns ID and Name
I want to select a one comma seperated string from Group table.
So IF I have 3 records as follows in group table
ID | Name
1 | Msh
2 | Nsh
3 | Lsh
I want to get a one comma seperated list of all three names like this Msh,Nsh,Lsh
How can I get this done is SQL CE ?
Try this..
DECLARE #COMMA VARCHAR(MAX)
SET #COMMA =''
SELECT #COMMA =#COMMA +name+',' FROM yourtablename
SELECT SUBSTRING(#COMMA,0,LEN(#COMMA))
You can develop a simple logic in SQL. This is a dummy code you can try and modify the code as per your requirements.
declare
i varchar2(100);
j varchar2(100);
begin
for i in (select name from avrajit)
loop
j:=i.name||','||j;
end loop;
dbms_output.put_line(j);
end;
---------------------------------------
OUTPUT
---------------------------------------
Hitesh,Sushil2,Mukul,Shyam,Nikheel,Avrajit,Sushil,
Statement processed.