Run table names pulled from sys.tables SQL Server 2008R2 - recursion

I need to identify tables that were created today by an interface, which I was able to do by using following query:
Note: The interface changes table names on daily basis.
SELECT [name] AS [TableName]
FROM sys.tables
WHERE NAME LIKE '_XYZExport_%'
AND CAST(create_date AS DATE) = CAST(GETDATE() AS DATE)
ORDER BY NAME
What I need:
Once the table names are pulled, I need dump its data into a new table. How can this be done easily?
Example:
Following tables returned from my queries:
_XYZExport_B02
_XYZExport_B12
_XYZExport_B22
I want to take these returned tables and insert their data into an existing Archive table using Union All.
Any help would be great!

You are on the right track with your "cursor" tag. I would recommend creating an insert statement and executing it each cursor loop.
DECLARE #TableName sysname
DECLARE #SQLInsert VARCHAR(100)
DECLARE TableNamesCursor CURSOR FAST_FORWARD READ_ONLY FOR
SELECT [name] AS [TableName]
FROM sys.tables
WHERE NAME LIKE '_XYZExport_%'
AND CAST(create_date AS DATE) = CAST(GETDATE() AS DATE)
ORDER BY NAME
OPEN TableNamesCursor
FETCH NEXT FROM TableNamesCursor INTO #TableName
WHILE ##FETCH_STATUS = 0
BEGIN
SET #SQLInsert = 'INSERT INTO ArchiveTable SELECT * FROM ' + #TableName
EXEC sp_executesql #SQLInsert
FETCH NEXT FROM TableNamesCursor INTO #TableName
END
CLOSE TableNamesCursor
DEALLOCATE TableNamesCursor
Hope that gets you going.
Noel

Related

Teradata Insert Count into Variable

Description what I am trying to do:
I have 2 environments one has data (X) second one has no data (Y).
I have done procedure which has input parameter P_TableName. It should check if in this table is any data and IF There is then we will take data to Y environment.
So Mostly it works but I have problem with one freaking simple thing ( I have not much experience in TD but in Oracle it would be a 10seconds).
I need to pass select count(*) from X to variable how to do that?.
I was trying by SET VAR = SELECT...
INSERT INTO VAR SELECT...
I was trying to make a variable for statement which is directly executing
SET v_sql_stmt = 'INSERT INTO ' || VAR|| ' SELECT COUNT(*) FROM ' || P_TableName;
CALL DBC.SYSEXECSQL(v_sql_stmt);
It's probably really simple thing but I can't find good solution for that. Please help
You'll have to open a cursor to fetch the results since you are running dynamic SQL. There is a good example in the Teradata help doc on Dynamic SQL:
CREATE PROCEDURE GetEmployeeSalary
(IN EmpName VARCHAR(100), OUT Salary DEC(10,2))
BEGIN
DECLARE SqlStr VARCHAR(1000);
DECLARE C1 CURSOR FOR S1;
SET SqlStr = 'SELECT Salary FROM EmployeeTable WHERE EmpName = ?';
PREPARE S1 FROM SqlStr;
OPEN C1 USING EmpName;
FETCH C1 INTO Salary;
CLOSE C1;
END;
You can't use INTO in Dynamic SQL in Teradata.
As a workaround you need to do a cursor returning a single row:
DECLARE cnt BIGINT;
DECLARE cnt_cursor CURSOR FOR S;
SET v_sql_stmt = ' SELECT COUNT(*) FROM ' || P_TableName;
PREPARE S FROM v_sql_stmt;
OPEN cnt_cursor;
FETCH cnt_cursor INTO cnt;
CLOSE cnt_cursor;

SQL Server triggers aren't working with Linq to SQL on ASP.NET

My work colleague is making the ASP.NET Web Forms application collecting data. I'm administrating SQL Server database of it. Based on databse he makes objects to Web Forms using Linq to SQL. He wanted me to make recodrds in Osoby to change dataDodania with date of generation the object and dataModyfikacji with date of last update. Having experience in PL/SQL I made simple triggers for this. The problem is that triggers work when I run SQL statements in SQL Server Management Studio 2008 nicely, but when used in application - they are omitted, not making changes needed. Here is triggers SQL code:
CREATE TRIGGER [dbo].[DodanieOsoby]
ON [dbo].[Osoby]
INSTEAD OF INSERT
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
INSERT INTO Osoby(dataDodania, dataModyfikacji, loginId, rola, imie, imieDrugie, nazwisko, plec, wiek,pESEL,wyksztalcenie,opieka,ulica, nrDom, nrLokal, miejscowosc, obszar, kodPoczty, telefonKontakt, telefonStacjo, email, zatrudnienie, stanowisko, przedsiebiorstwo)
SELECT GETDATE(), GETDATE(), loginId, rola, imie, imieDrugie, nazwisko, plec, wiek, pESEL, wyksztalcenie,opieka,ulica, nrDom, nrLokal, miejscowosc, obszar, kodPoczty, telefonKontakt, telefonStacjo, email, zatrudnienie, stanowisko, przedsiebiorstwo
FROM inserted
END
And for UPDATE of Osoby...
CREATE TRIGGER [dbo].[AktualizacjaOsoby]
ON [dbo].[Osoby]
AFTER UPDATE
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
UPDATE Osoby
SET dataModyfikacji = GETDATE()
WHERE id in
(SELECT DISTINCT id from Inserted)
END
Possible this be helpful for you (if dbo.Osoby is view) -
ALTER TRIGGER dbo.trg_IOIU_vw_WorkOut
ON dbo.vw_WorkOut
INSTEAD OF INSERT, UPDATE
AS BEGIN
SET NOCOUNT ON
SET XACT_ABORT ON
DECLARE
#WorkOutID BIGINT
, #DateOut DATETIME
, #EmployeeID INT
DECLARE workout CURSOR LOCAL READ_ONLY FAST_FORWARD FOR
SELECT
WorkOutID
, DateOut
, EmployeeID
FROM INSERTED
OPEN workout
FETCH NEXT FROM workout INTO
#WorkOutID
, #DateOut
, #EmployeeID
WHILE ##FETCH_STATUS = 0 BEGIN
IF NOT EXISTS(
SELECT 1
FROM dbo.WorkOut
WHERE WorkOutID = #WorkOutID
)
BEGIN
INSERT INTO dbo.WorkOut
(
EmployeeID
, DateOut
)
SELECT
#EmployeeID
, #DateOut
SELECT SCOPE_IDENTITY() -- if you use LINQ need return new ID to client
END
ELSE BEGIN
UPDATE dbo.WorkOut
SET
EmployeeID = #EmployeeID
, DateOut = #DateOut
WHERE WorkOutID = #WorkOutID
END
FETCH NEXT FROM workout INTO
#WorkOutID
, #DateOut
, #EmployeeID
END
CLOSE workout
DEALLOCATE workout
END

Create and insert a row into the table in stored procedure

create or replace procedure sample
as
ID VARCHAR(20);
BEGIN
execute immediate
'CREATE GLOBAL TEMPORARY TABLE UPDATE_COLUMN_NO_TP
(
NAME VARCHAR2(256)
)';
INSERT INTO UPDATE_COLUMN_NO_TP
SELECT SRC_PK_COLUMNS.PK_KEY
FROM SRC_PK_COLUMNS
WHERE NOT EXISTS (
SELECT 1
FROM TGT_PK_COLUMNS
WHERE TGT_PK_COLUMNS.ID = SRC_PK_COLUMNS.ID);
END;
Error is:
The table is no exist.
So, I want a best solution for this scenario. In my stored procedure I have 10 temporary tables. All are all dynamic creations and inserts.
Table UPDATE_COLUMN_NO_TP not exists at compile time, so you got the error.
If you created a table dynamically, you should access it dynamically.
And pay attention to Mat's comment about essence of GTT.
execute immediate '
INSERT INTO UPDATE_COLUMN_NO_TP
SELECT SRC_PK_COLUMNS.PK_KEY
FROM SRC_PK_COLUMNS
WHERE NOT EXISTS (
SELECT 1
FROM TGT_PK_COLUMNS
WHERE TGT_PK_COLUMNS.ID = SRC_PK_COLUMNS.ID
)
';

Using nvarchar(MAX) to build query, but conversion fails in where clause

I have a stored procedure that uses a variable called #Command (nvarchar(MAX)). I then add parameters accordingly based on given input.
declare #Command nvarchar(max)
if(#CaseFileID IS NOT NULL)
BEGIN
select #Command='
select [ServerCredentialsID],[CaseFileID],EIKSLT.[LocationType],EPT.PaymentType,[TaskID],[DateActive]
,[LengthOfPurchase],[Username],[Password],[IPDomain],[Port],[DES],[Website],[AmountPaid],[Latitude]
,[Longitude],[HasAttachments],[TimeStamp],[CaseElement],[Temporary],[StatusID]
FROM Element17a_IKSServerCredentials EIKSSC
JOIN ElementsIKSLocationTypes EIKSLT ON EIKSSC.LocationBeingUsedID= EIKSLT.IKSLocationBeingUsedID
JOIN ElementsPaymentTypes EPT ON EIKSSC.PaymentMethodID=EPT.PaymentTypeID
where EIKSSC.CaseFileID='''+cast(#CaseFileID as nvarchar(MAX))+''' '
#CaseFileID is declared as an int, and in the table it is an int. When I try
where EIKSSC.CaseFileID = ' + #CaseFileID + ' '
then the value doesn't even show (in the error it looks like "EIKSSC.CaseFileID= '" )
I just don't get it.
NOTE: SQL Server 2008 Management Studio
It's because #CaseFileID is VARCHAR even though you don't show it.
Your IF should be
if(#CaseFileID > '')
And if even that doesn't work, then you need to swap to LEFT joins because INNER JOINs will remove records that cannot be matched in the other 2 tables.
Finally, because CaseFileID is an int, you don't need the quotes. Even though SQL Server will implicitly cast '9' to the integer 9 in the WHERE clause, it's just not necessary.
declare #Command nvarchar(max)
if(#CaseFileID > '')
BEGIN
select #Command='
select [ServerCredentialsID],[CaseFileID],EIKSLT.[LocationType],EPT.PaymentType,[TaskID],[DateActive]
,[LengthOfPurchase],[Username],[Password],[IPDomain],[Port],[DES],[Website],[AmountPaid],[Latitude]
,[Longitude],[HasAttachments],[TimeStamp],[CaseElement],[Temporary],[StatusID]
FROM Element17a_IKSServerCredentials EIKSSC
LEFT JOIN ElementsIKSLocationTypes EIKSLT ON EIKSSC.LocationBeingUsedID= EIKSLT.IKSLocationBeingUsedID
LEFT JOIN ElementsPaymentTypes EPT ON EIKSSC.PaymentMethodID=EPT.PaymentTypeID
where EIKSSC.CaseFileID='+cast(#CaseFileID as nvarchar(MAX))

how to insert the value into a table type through a select statement in oracle?

I am a beginner in Oracle. I created the table type as like as follows:
TYPE metertable IS TABLE OF pseb.metermaster.meterid%type;
I dnt know how to insert the value into that table type. I need to store the whole resultset of the following query into the table type.
select distinct(meterid)
from pseb.consumerfeedermetermapper
where feederid in (select distinct (fm.FeederID)
from pseb.feedermaster fm,pseb.consumerfeedermetermapper cfm
where fm.substationid=v_v_type
and cfm.feederid=fm.feederid
and cfm.FeederID>0)
and meterid >0
order by meterid;
Help me to do that.
Use BULK COLLECT to select the data into a variable of that type:
declare
mt metertable;
begin
select distinct(meterid)
bulk collect into mt
from pseb.consumerfeedermetermapper
where feederid in (select distinct (fm.FeederID)
from pseb.feedermaster fm,pseb.consumerfeedermetermapper cfm
where fm.substationid=v_v_type
and cfm.feederid=fm.feederid
and cfm.FeederID>0)
and meterid >0
order by meterid;
-- Now use mt...
end;
I had the same issue, and this code help me :
SET SERVEROUTPUT ON
DECLARE
TYPE t_bulk_collect_test_tab IS TABLE OF bulk_collect_test%ROWTYPE;
l_tab t_bulk_collect_test_tab;
l_cursor SYS_REFCURSOR;
BEGIN
-- Way 1
OPEN l_cursor FOR 'SELECT * FROM bulk_collect_test';
FETCH l_cursor
BULK COLLECT INTO l_tab;
CLOSE l_cursor;
DBMS_OUTPUT.put_line('Dynamic FETCH : ' || l_tab.count);
-- Way 2
EXECUTE IMMEDIATE 'SELECT * FROM bulk_collect_test' BULK COLLECT INTO l_tab;
DBMS_OUTPUT.put_line('Dynamic EXECUTE: ' || l_tab.count);
END;
/
http://www.dba-oracle.com/plsql/t_plsql_dynamic.htm
declare
type tab_type is table of consumerfeedermetermapper%rowtype;
tab_t tab_type;
begin
select distinct(meterid) bulk collect into tab_t
from pseb.consumerfeedermetermapper
where feederid in (select distinct (fm.FeederID)
from pseb.feedermaster fm,pseb.consumerfeedermetermapper cfm
where fm.substationid=v_v_type
and cfm.feederid=fm.feederid
and cfm.FeederID>0)
and meterid >0
order by meterid;
end;
You can use the above code

Resources