can one use temp tables in teradata - sql-server

Is there an equivalent for this sql server tsql in teradata:
IF OBJECT_ID('tempdb..#SomeTempTable') IS NOT NULL DROP TABLE #SomeTempTable;
CREATE TABLE #SomeTempTable (Bla NVARCHAR(255));
INSERT INTO #SomeTempTable
SELECT N'a'
UNION ALL
SELECT N'B'

There's no equivalent for the 1st statement, there might be a Stored Procedure for it like this:
REPLACE PROCEDURE Drop_Table_If_Exists
(
IN db_name VARCHAR(128) CHARACTER SET UNICODE,
IN tbl_name VARCHAR(128) CHARACTER SET UNICODE,
OUT msg VARCHAR(400) CHARACTER SET UNICODE
) SQL SECURITY INVOKER
BEGIN
DECLARE full_name VARCHAR(361) CHARACTER SET UNICODE;
DECLARE sql_stmt VARCHAR(500) CHARACTER SET UNICODE;
DECLARE exit HANDLER FOR SQLCODE 'T3807'--SQLEXCEPTION
BEGIN
IF SQLCODE = 3807 THEN SET msg = full_name || ' doesn''t exist.';
ELSE
RESIGNAL;
END if;
END;
SET full_name = '"' || COALESCE(db_name,DATABASE) || '"."' || tbl_name || '"';
SET sql_stmt = 'DROP TABLE ' || full_name || ';';
EXECUTE IMMEDIATE sql_stmt;
SET msg = full_name || ' dropped.';
END;
A VOLATILE table exists only within your current session (i.e. the same name might be used in different sessions for different tables) and is automatically dropped when the session disconnects. When you keep the naming convention (name of a temporary starts with #) you probably don't need the conditional Drop (you should know if you already created this table in the current session):
CREATE VOLATILE TABLE #SomeTempTable(
Bla VARCHAR(255) CHARACTER SET UNICODE)
ON COMMIT PRESERVE ROWS;
Caution, if you don't specify the Primary Index it will default to a NUPI on the first column.
The Select has a strange restriction, you need a FROM when you do a Set Operation like UNION/INTERSECT/EXCEPT. Workaround is either a dummy view (similar to Oracle's DUAL table) like this:
replace view dummy as select 1 as x;
INSERT INTO #SomeTempTable
SELECT 'a' FROM dummy
UNION ALL
SELECT 'B' FROM dummy
or a similar CTE:
INSERT INTO #SomeTempTable
WITH dummy AS (select 1 as x)
SELECT 'a' FROM dummy
UNION ALL
SELECT 'B' FROM dummy

Related

Range partitioning tables with data in DB2 LUW

First of all my question will be, if there is a way of auto-generation partitions (like interval in Oracle for range partitioning) while inserting data into the partitioned table in DB2?
At the moment I have a schema with some hundreds of tables, which are not partitioned. And I suppose to partition them.
My steps will be:
rename all the tables to OLD_table_name
execute DDLs for those tables but already partitioned (by load_id column int data type)
execute for all, insert into table_name select * from OLD_table_name
...and here it starts.
(Of course the process must be automatically and I don't know which values contain load_id column + they will be all different for all the tables, otherwise it would be possible to generate simply alter statements and execute them).
Therefore I would go for cursor.
For the moment I have solution which is working but I don't like it:
BEGIN
FOR CL AS MYCURS INSENSITIVE CURSOR FOR
select distinct 'alter table '||tb_nm||'
add partition PART_'||lpad(load_id,5,0)||'
starting from '||load_id||'
ending at '||load_id v_alt
from (
select load_id,'Table_01' tb_nm from Table_01
union
select load_id ,'Table_02'from Table_02
union
....
/*I have generated this union statements for whole set of tables*/)
do
execute immediate v_alt;
end for;
end
Also, I have tried some more elegant (on my opinion) variant, but didn't sucseed:
BEGIN
DECLARE v_stmnt VARCHAR(1000);
DECLARE v_check_val int;
DECLARE v_prep_stmnt STATEMENT;
for i as (select table_name
from sysibm.tables
where TABLE_SCHEMA ='shema_name'
)
do
SET v_stmnt = 'set ? = (SELECT distinct(load_id) FROM '||table_name||')';
PREPARE v_prep_stmnt FROM v_stmnt;
/*and here I stuck. I assume there must be possibility to run next execute as well in loop, but
all my attempts were not succsesfull*/
--EXECUTE v_prep_stmnt into v_check_val ;
end for;
END
Would highly appreciate any hint.
Try something like this:
--#SET TERMINATOR #
SET SERVEROUTPUT ON#
BEGIN
DECLARE L_TABSCHEMA VARCHAR(128) DEFAULT 'SCHEMA_NAME';
DECLARE L_COLNAME VARCHAR(128) DEFAULT 'LOAD_ID';
DECLARE L_VALUE INT;
DECLARE L_STMT VARCHAR(1024);
DECLARE SQLSTATE CHAR(5);
DECLARE C1 CURSOR FOR S1;
FOR I AS
SELECT TABNAME
FROM SYSCAT.COLUMNS
WHERE TABSCHEMA = L_TABSCHEMA AND COLNAME = L_COLNAME
DO
PREPARE S1 FROM 'SELECT DISTINCT(' || L_COLNAME || ') FROM ' || L_TABSCHEMA || '."' || I.TABNAME ||'"';
OPEN C1;
L1: LOOP
FETCH C1 INTO L_VALUE;
IF SQLSTATE<>'00000' THEN LEAVE L1; END IF;
SET L_STMT =
'alter table ' || L_TABSCHEMA || '."' || I.TABNAME || '" '
||'add partition PART_' || lpad(L_VALUE, 5, 0) || ' starting from ' || L_VALUE || ' ending at ' || L_VALUE;
--CALL DBMS_OUTPUT.PUT_LINE(L_STMT);
EXECUTE IMMEDIATE L_STMT;
END LOOP;
CLOSE C1;
END FOR;
END
#

Show a few columns in a stored procedure based on a parameter

I have a parameter in my stored procedure called internal. If "internal" = yes then I want to display an additional 2 columns in my results. If it's no I don't want to display these columns.
I can do a case statement and then I can set the column to be empty but the column name will still be returned in the results.
My questions are:
Is there a way not to return these 2 columns in the results at all?
Can I do it in one case statement and not a separate case statement for each column?
Thank you
No, CASE is a function, and can only return a single value.
And According to your comment:-
The issue with 2 select statements are that it's a major complicated
select statement and I really don't want to have to have the whole
select statement twice.
so you can use the next approach for avoid duplicate code:-
Create procedure proc_name (#internal char(3), .... others)
as
BEGIN
declare #AddationalColumns varchar(100)
set #AddationalColumns = ''
if #internal = 'Yes'
set #AddationalColumns = ',addtionalCol1 , addtionalCol2'
exec ('Select
col1,
col2,
col3'
+ #AddationalColumns +
'From
tableName
Where ....
' )
END
Try IF Condition
IF(internal = 'yes')
BEGIN
SELECT (Columns) FROM Table1
END
ELSE
BEGIN
SELECT (Columns With additional 2 columns) FROM Table1
END
You can do something like this solution. It allows you to keep only one copy of code if it's so important but you will have to deal with dynamic SQL.
CREATE TABLE tab (col1 INT, col2 INT, col3 INT);
GO
DECLARE #internal BIT = 0, #sql NVARCHAR(MAX)
SET #sql = N'SELECT col1 ' + (SELECT CASE #internal WHEN 1 THEN N', col2, col3 ' ELSE N'' END) + N'FROM tab'
EXEC sp_executesql #sql
GO
DROP TABLE tab
GO
Another option is to create a 'wrapper' proc. Keep your current one untouched.
Create a new proc which executes this (pseudo code):
create proc schema.wrapperprocname (same #params as current proc)
as
begin
Create table #output (column list & datatypes from current proc);
insert into #output
exec schema.currentproc (#params)
if #internal = 'Yes'
select * from #output
else
select columnlist without the extra 2 columns from #output
end
This way the complex select statement remains encapsulated in the original proc.
Your only overhead is keeping the #output table & select lists in in this proc in sync with any changes to the original proc.
IMO it's also easier to understand/debug/tune than dynamic sql.

Restart initial id of table with using MAX() method

I am doing some changes on my table and I couldn't figure out the problem.
This is my SQL script;
ALTER TABLE X ALTER COLUMN X_ID RESTART WITH (SELECT MAX(X_ID) FROM X);
Altough I used AS instead of WITH and tried other combinations, I couldn't find the exact syntax. (By the way, I cannot set this property in the initialization, I got to do it after creation of the table )
When looking at the syntax for ALTER TABLE you will find that you can only use a constant, e.g., "RESTART WITH 12345". A query itself is not possible. For automation you would need to break it up, use a variable, generate the ALTER statement and execute it.
Assuming this is for DB2 for LUW, you can automate the process of resetting identity values with some dynamic SQL:
begin
declare curmax bigint;
for r as select tabschema, tabname, colname, nextcachefirstvalue, seqid
from syscat.colidentattributes where tabschema = current_schema
do
prepare s from
'select max(' || r.colname || ') from ' ||
rtrim(r.tabschema) || '.' || r.tabname;
begin
declare c cursor for s;
open c;
fetch c into curmax;
close c;
end;
if curmax >= r.nextcachefirstvalue
then
execute immediate
'alter table ' || rtrim(r.tabschema) || '.' || r.tabname ||
' alter column ' || r.colname || ' restart with ' || varchar(curmax+1);
end if;
end for;
end
You may need to change the data type of curmax if your identities are not integer, and adjust the query against syscat.colidentattributes to use the appropriate schema name.

Removing Identity_Insert from a Temp Table that is Generated Dynamically

I've got a Stored Procedure that I want to audit all the changes it makes to many tables. This bit of code repeated down the SP but with different table names. Once that piece of script is finish I then copy the contents of the temp table to my audit table which works well.
I have a problem with one table which bring back this message: An explicit value for the identity column in table '#MyTempTable' can only be specified when a column list is used and IDENTITY_INSERT is ON.
I'm lazy, I don't want to specify all the column names. Is there a way to remove the identity from the temp table after I created it?
--Create Temp Audit Table
IF OBJECT_ID('tempdb..#MyTempTable') IS NOT NULL drop table #MyTempTable;
select top 0 * into #MyTempTable from TabletoAudit
--Do changes and record into TempTable
UPDATE TabletoAudit
SET
series_nm = #newseries,
UPDATED_DT = GetDate()
OUTPUT deleted.* INTO #MyTempTable
WHERE
mach_type_cd = #mtype
AND
brand_id = #brand
AND
series_nm = #oldseries
--Copy Contents from Temp table to Audit Table
If the identity column is the first column (usually it is) then you can also:
assuming data type INT, column name originalid
SELECT top 0 CONVERT(INT,0)myid,* into #MyTempTable from TabletoAudit
ALTER TABLE #MyTempTable DROP COLUMN originalid
EXEC tempdb.sys.sp_rename N'#MyTempTable.myid', N'originalid', N'COLUMN'
I spent over a day researching into this but now finally found a solution. Simply when I create it, create it without the Identity in the first place. I did this by creating a dynamic script to create a temp table based on another and don't add identity.
SET NOCOUNT ON;
IF OBJECT_ID('tempdb..##MyTempTable') IS NOT NULL drop table ##INSERTED7;
SET NOCOUNT ON;
DECLARE #sql NVARCHAR(MAX);
DECLARE #CreateSQL NVARCHAR(MAX);
SET #sql = N'SELECT * FROM TabletoAudit;';
SELECT #CreateSQL = 'CREATE TABLE ##MyTempTable(';
SELECT
#CreateSQL = #CreateSQL + CASE column_ordinal
WHEN 1 THEN '' ELSE ',' END
+ name + ' ' + system_type_name + CASE is_nullable
WHEN 0 THEN ' not null' ELSE '' END
FROM
sys.dm_exec_describe_first_result_set (#sql, NULL, 0) AS f
ORDER BY column_ordinal;
SELECT #CreateSQL = #CreateSQL + ');';
EXEC sp_executesql #CreateSQL;
SET NOCOUNT OFF;
I also changed the Temp Table to a Global Temp Table for it to work.

How to detect interface break between stored procedure

I am working on a large project with a lot of stored procedures. I came into the following situation where a developer modified the arguments of a stored procedure which was called by another stored procedure.
Unfortunately, nothing prevents the ALTER PROC to complete.
Is there a way to perform those checks afterwards ?
What would be the guidelines to avoid getting into that kind of problems ?
Here is a sample code to reproduce this behavior :
CREATE PROC Test1 #arg1 int
AS
BEGIN
PRINT CONVERT(varchar(32), #arg1)
END
GO
CREATE PROC Test2 #arg1 int
AS
BEGIN
DECLARE #arg int;
SET #arg = #arg1+1;
EXEC Test1 #arg;
END
GO
EXEC Test2 1;
GO
ALTER PROC Test1 #arg1 int, #arg2 int AS
BEGIN
PRINT CONVERT(varchar(32), #arg1)
PRINT CONVERT(varchar(32), #arg2)
END
GO
EXEC Test2 1;
GO
DROP PROC Test2
DROP PROC Test1
GO
Sql server 2005 has a system view sys.sql_dependencies that tracks dependencies. Unfortunately, it's not all that reliable (For more info, see this answer). Oracle, however, is much better in that regard. So you could switch. There's also a 3rd party vendor, Redgate, who has Sql Dependency Tracker. Never tested it myself but there is a trial version available.
I have the same problem so I implemented my poor man's solution by creating a stored procedure that can search for strings in all the stored procedures and views in the current database. By searching on the name of the changed stored procedure I can (hopefully) find EXEC calls.
I used this on sql server 2000 and 2008 so it probably also works on 2005. (Note : #word1, #word2, etc must all be present but that can easily be changed in the last SELECT if you have different needs.)
CREATE PROCEDURE [dbo].[findWordsInStoredProceduresViews]
#word1 nvarchar(4000) = null,
#word2 nvarchar(4000) = null,
#word3 nvarchar(4000) = null,
#word4 nvarchar(4000) = null,
#word5 nvarchar(4000) = null
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
-- create temp table
create table #temp
(
id int identity(1,1),
Proc_id INT,
Proc_Name SYSNAME,
Definition NTEXT
)
-- get the names of the procedures that meet our criteria
INSERT #temp(Proc_id, Proc_Name)
SELECT id, OBJECT_NAME(id)
FROM syscomments
WHERE OBJECTPROPERTY(id, 'IsProcedure') = 1 or
OBJECTPROPERTY(id, 'IsView') = 1
GROUP BY id, OBJECT_NAME(id)
-- initialize the NTEXT column so there is a pointer
UPDATE #temp SET Definition = ''
-- declare local variables
DECLARE
#txtPval binary(16),
#txtPidx INT,
#curText NVARCHAR(4000),
#counterId int,
#maxCounterId int,
#counterIdInner int,
#maxCounterIdInner int
-- set up a double while loop to get the data from syscomments
select #maxCounterId = max(id)
from #temp t
create table #tempInner
(
id int identity(1,1),
curName SYSNAME,
curtext ntext
)
set #counterId = 0
WHILE (#counterId < #maxCounterId)
BEGIN
set #counterId = #counterId + 1
insert into #tempInner(curName, curtext)
SELECT OBJECT_NAME(s.id), text
FROM syscomments s
INNER JOIN #temp t
ON s.id = t.Proc_id
WHERE t.id = #counterid
ORDER BY s.id, colid
select #maxCounterIdInner = max(id)
from #tempInner t
set #counterIdInner = 0
while (#counterIdInner < #maxCounterIdInner)
begin
set #counterIdInner = #counterIdInner + 1
-- get the pointer for the current procedure name / colid
SELECT #txtPval = TEXTPTR(Definition)
FROM #temp
WHERE id = #counterId
-- find out where to append the #temp table's value
SELECT #txtPidx = DATALENGTH(Definition)/2
FROM #temp
WHERE id = #counterId
select #curText = curtext
from #tempInner
where id = #counterIdInner
-- apply the append of the current 8KB chunk
UPDATETEXT #temp.definition #txtPval #txtPidx 0 #curtext
end
truncate table #tempInner
END
-- check our filter
SELECT Proc_Name, Definition
FROM #temp t
WHERE (#word1 is null or definition LIKE '%' + #word1 + '%') AND
(#word2 is null or definition LIKE '%' + #word2 + '%') AND
(#word3 is null or definition LIKE '%' + #word3 + '%') AND
(#word4 is null or definition LIKE '%' + #word4 + '%') AND
(#word5 is null or definition LIKE '%' + #word5 + '%')
ORDER BY Proc_Name
-- clean up
DROP TABLE #temp
DROP TABLE #tempInner
END
You can use sp_refreshsqlmodule to attempt to re-validate SPs (this also updates dependencies), but it won't validate this particular scenario with parameters at the caller level (it will validate things like invalid columns in tables and views).
http://www.mssqltips.com/tip.asp?tip=1294 has a number of techniques, including sp_depends
Dependency information is stored in the SQL Server metadata, including parameter columns/types for each SP and function, but it isn't obvious how to validate all the calls, but it is possible to locate them and inspect them.

Resources