How to export Varbyte in Teradata - teradata

I have a table with example data as follows:
Num JobId
1 12345678
where Num is of Integer datatype, and JobId is of Varbyte datatype.
I need to extract it, and the TPT script I have used for this is:
USING CHARACTER SET UTF8
DEFINE JOB EXPORT_DELIMITED_FILE
DESCRIPTION 'Export' ( DEFINE SCHEMA FILE_SCHEMA (
Num INTEGER,
JobID Varbyte(16)
);
DEFINE OPERATOR SQL_SELECTOR
TYPE SELECTOR
SCHEMA FILE_SCHEMA ATTRIBUTES
(
VARCHAR PrivateLogName = 'selector_log',
VARCHAR TdpId = '192.168.xx.xxx',
VARCHAR UserName = 'dbc', VARCHAR UserPassword = 'dbc',
VARCHAR SelectStmt = 'SELECT * FROM AdventureWorksDW.DB1_TB1;',
DEFINE OPERATOR FILE_WRITER
TYPE DATACONNECTOR CONSUMER
SCHEMA *
ATTRIBUTES
(
VARCHAR PrivateLogName = 'dataconnector_log',
VARCHAR DirectoryPath = 'filepath',
VARCHAR FileName = 'DB1_TB1.csv',
VARCHAR FORMAT= 'DELIMITED', //delimited doesn't work
VARCHAR TextDelimiter= '|',
VARCHAR OpenMode = 'Write'
);
APPLY TO OPERATOR (FILE_WRITER)
SELECT * FROM OPERATOR (SQL_SELECTOR);
);
I need the csv file in the format:
1 | 12345678
How to achieve this?

Binary data is not supported for delimited format. But you can transform it to a string using from_bytes in your select:
USING CHARACTER SET UTF8
DEFINE JOB EXPORT_DELIMITED_FILE
DESCRIPTION 'Export'
(
APPLY TO OPERATOR
( $FILE_WRITER[1]
ATTR ( VARCHAR PrivateLogName = 'dataconnector_log',
VARCHAR DirectoryPath = 'filepath',
VARCHAR FileName = 'DB1_TB1.csv',
VARCHAR FORMAT= 'DELIMITED',
VARCHAR TextDelimiter= '|',
VARCHAR OpenMode = 'Write'
)
)
SELECT *
FROM OPERATOR
( $SELECTOR[1]
ATTR
( PrivateLogName = 'selector_log',
TdpId = '192.168.xx.xxx',
UserName = 'dbc',
UserPassword = 'dbc',
SelectStmt = 'SELECT num, from_bytes(jobid, ''base16'') FROM td01.testtab;'
)
);
);

Related

Issues with postgresql-11 partitioning and primary key autoincrement

Primary key on partitioned tables is incremented by n(n>1) and not by 1.
Tried to rewrite plpgsql in numerous different ways with no luck.
There must be something I am not understanding.
CREATE SCHEMA IF NOT EXISTS some_record_pool;
CREATE SEQUENCE some_record_pkey_seq;
create table some_record
(
id BIGINT not null DEFAULT nextval('some_record_pkey_seq'::regclass),
device_id bigint,
device_type bigint,
record_time timestamp,
module_serial_number bigint,
module_id bigint,
message_type bigint,
event_code bigint,
device_status bytea,
sequence_number bigint,
data_bytes bigint,
device_data bytea,
active boolean,
deleted boolean,
created_time timestamp default now() not null,
created_on timestamp with time zone default now() not null,
updated_on timestamp with time zone default now() not null
);
CREATE INDEX idx_device_id
ON public.some_record USING brin
(device_id)
TABLESPACE pg_default;
CREATE INDEX idx_module_id
ON public.some_record USING brin
(module_id)
TABLESPACE pg_default;
CREATE INDEX idx_er_created_time
ON public.some_record (cast(created_time as DATE));
----- CREATE TRIGGER ----------
CREATE OR REPLACE FUNCTION some_record_insert_function()
RETURNS TRIGGER AS
$$
DECLARE
partition_date TEXT;
partition_name TEXT;
start_of_month TEXT;
end_of_next_month TEXT;
BEGIN
partition_date := to_char(NEW.created_time, 'YYYY_MM');
partition_name := 'some_record_' || partition_date;
start_of_month := to_char((NEW.created_time), 'YYYY-MM') || '-01';
end_of_next_month := to_char((NEW.created_time + interval '1 month'), 'YYYY-MM') || '-01';
IF NOT EXISTS
(SELECT 1
FROM information_schema.tables
WHERE table_name = partition_name)
THEN
RAISE NOTICE 'A partition has been created %', partition_name;
EXECUTE format(
E'CREATE TABLE some_record_pool.%I ' ||
E'(CHECK ( date_trunc(\'day\', created_time) >= ''%s'' ' ||
E'AND date_trunc(\'day\', created_time) < ''%s'')) INHERITS (public.some_record)',
partition_name, start_of_month, end_of_next_month);
-- EXECUTE format('GRANT SELECT ON TABLE %I TO readonly',
-- partition_name); -- use this if you use role based permission
ELSE
RAISE NOTICE 'A partition DOES NOT EXIST %', partition_name;
END IF;
EXECUTE format(
'INSERT INTO some_record_pool.%I (device_id, device_type, ' ||
'record_time, module_serial_number, module_id, message_type, ' ||
'event_code, device_status, sequence_number, data_bytes, device_data,' ||
' active, deleted) VALUES($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13)',
partition_name) using NEW.device_id, NEW.device_type,
NEW.record_time, NEW.module_serial_number, NEW.module_id, NEW.message_type,
NEW.event_code, NEW.device_status, NEW.sequence_number, NEW.data_bytes,
NEW.device_data, NEW.active, NEW.deleted;
RETURN NEW;
END
$$
LANGUAGE plpgsql;
CREATE TRIGGER insert_some_record_trigger
BEFORE INSERT ON public.some_record
FOR EACH ROW EXECUTE PROCEDURE public.some_record_insert_function();
--- INSERTING DATA FOR TESTING
INSERT INTO some_record (
event_record_id, timestamp, event_description_id, event_source_label, event_source_track, event_source_direction,
measurement_description, measurement_value, hw_address_module_id, hw_address_rlc_address, sub_system_source,
event_type, device_id, active, deleted) VALUES(1, 2, to_timestamp('1953-10-21 14:30:46.555337', 'YYYY-MM-DD HH:MI:SS.US'), 1, 1, 1, 1, NULL, 1, 9, E'9 B
00000000 92 FF 3C 00 7F 00 00 03 E8 .ÿ<.....è
', TRUE, FALSE, to_timestamp('2019-10-21 14:30:46.555337', 'YYYY-MM-DD HH:MI:SS.US'), to_timestamp('2019-10-21 14:30:46.555337', 'YYYY-MM-DD HH:MI:SS.US'));
The point of the code is to auto create partitions and insert data if partition exists.
Primary key should be incremented by one but it is not behaving as such
expected output on only one run is id: 1
Working solution tested on postgres 12 is the following:
/** TABLE PARTITIONING EVENT RECORD **/
-- CREATE PROPER SCHEMA
CREATE SCHEMA IF NOT EXISTS test_par_pool;
-- CREATE PROPER TABLE
CREATE TABLE test_part
(
id bigserial not null
constraint test_part_pkey
primary key,
device_id bigint,
device_type bigint,
record_time timestamp,
module_serial_number bigint,
module_id bigint,
message_type bigint,
event_code bigint,
device_status bytea,
sequence_number bigint,
data_bytes bigint,
device_data bytea,
active boolean,
deleted boolean,
created_time timestamp default now() not null,
created_on timestamp with time zone default now() not null,
updated_on timestamp with time zone default now() not null
);
-- CREATE MINIMAL INDEXES
CREATE INDEX idx_device_id
ON public.test_part USING brin
(device_id)
TABLESPACE pg_default;
CREATE INDEX idx_module_id
ON public.test_part USING brin
(module_id)
TABLESPACE pg_default;
CREATE INDEX idx_er_created_time
ON public.test_part (cast(created_time as DATE));
-- CREATE INSERT FUNCTIONS
CREATE OR REPLACE FUNCTION test_par_insert_function()
RETURNS TRIGGER AS
$$
DECLARE
partition_date TEXT;
partition TEXT;
start_of_month TEXT;
end_of_next_month TEXT;
stmt TEXT;
BEGIN
partition_date := to_char(NEW.created_time, 'YYYY_MM');
partition := TG_RELNAME || '_' || partition_date;
start_of_month := to_char((NEW.created_time), 'YYYY-MM') || '-01';
end_of_next_month := to_char((NEW.created_time + interval '1 month'), 'YYYY-MM') || '-01';
IF NOT EXISTS(SELECT relname FROM pg_class WHERE relname = partition) THEN
RAISE NOTICE 'A partition has been created %',partition;
stmt = 'CREATE TABLE test_par_pool.' || partition || ' (check (date_trunc(''day'', created_time) >= '
|| chr(39) || start_of_month || chr(39)
|| ' AND date_trunc(''day'', created_time) < '
|| chr(39) || end_of_next_month
|| chr(39) || ' )) INHERITS ( public.' || TG_RELNAME ||
');';
EXECUTE stmt;
END IF;
EXECUTE 'INSERT INTO test_par_pool.' || partition ||
' SELECT( public.' || TG_RELNAME || ' ' || quote_literal(NEW) || ').* RETURNING id;';
RETURN NULL;
END
$$
LANGUAGE plpgsql;
-- CREATE TRIGGER
CREATE TRIGGER insert_test_part_trigger
BEFORE INSERT ON public.test_part
FOR EACH ROW EXECUTE PROCEDURE public.test_par_insert_function();

Textbox control can't accept different data types of input

I would like to search student by using Student ID OR Student Name. So I wrote my SELECT Statement like this:
SELECT * FROM [student] WHERE ([S_FName] LIKE '%' + #S_FName + '%') OR (SID =#SID)
However, both parameters #S_FName & #SID are sharing the same textbox control to let users search student. S_FName is varchar(50) and SID is int
I can't really search student by using student name or student ID by using single textbox. I keep getting the error:
Conversion failed when converting the nvarchar value 'student1' to data type int.]
Use the same search term, entered by the user, for both comparisons.
For the INT, convert it to a string first.
Another choice would be to convert the search term to an INT, but then you'd have to have special handling for non-numeric values.
create table Student
( StudentID int,
StudentName nvarchar(80) )
insert into Student ( StudentID, StudentName ) values
( 10123, 'Archimedes' ),
( 74701, 'Beatrice' ),
( 84448, 'Casandra' ),
( 99599, 'Archibald' )
declare #Search nvarchar(80)
set #Search = 'Arch'
select * from Student
where ( StudentName like '%' + #Search + '%' )
or ( cast(StudentID as nvarchar(20)) = #Search )
set #Search = '74701'
select * from Student
where ( StudentName like '%' + #Search + '%' )
or ( cast(StudentID as nvarchar(20)) = #Search )
If you have SQL Server 2012 or later, you can use Try_Convert to simplify.
select * from Student
where ( StudentName like N'%' + #Search + N'%' )
or ( StudentID = Try_Convert(int,#Search) )
you have to pass one parameter, because Textbox is same
and you must convert id to varchar so that type of id and fname is equal
so you can Follow the code below
SELECT [S_FName], SID, CAST(SID AS
varchar(50)) + '-' + S_FName AS S_FName_ID
FROM Coding_view
WHERE (CAST(SID AS varchar(50)) + '-' + S_FName LIKE
N'%Behmagham%')
good luck

i cannot call null data row in sqlite

Why I cannot call null data row when I use IS NULL in sqlite
select roomkeyID from roomkey where dateOfReturn is null;
CREATE TABLE ROOMKEY (
roomkeyID VARCHAR(10) not null primary key,
roomID VARCHAR(10) not null,
keyID VARCHAR(10) not null,
dateOfIssue DATETIME,
dateOfReturn DATETIME,
FOREIGN KEY (roomID) REFERENCES ROOM(roomID),
FOREIGN KEY (keyID ) REFERENCES KEY(keyID )
)
"RK000001","R106","K0003","12/17/2015"," "
"RK000090","R101","K0002","12/12/2015"," "
From the example it seems that in the field dateOfReturn you do not have NULL values, but strings with a space inside. If this is true then you have to change your query to:
select roomkeyID from roomkey where dateOfReturn is null or dateOfReturn = ' '

How to separate (split) string with comma in SQL Server stored procedure

I have a checkboxlist. The selected (checked) items are stored in List<string> selected.
For example, value selected is monday,tuesday,thursday out of 7 days
I am converting List<> to a comma-separated string, i.e.
string a= "monday,tuesday,thursday"
Now, I am passing this value to a stored procedure as a string. I want to fire query like:
Select *
from tblx
where days = 'Monday' or days = 'Tuesday' or days = 'Thursday'`
My question is: how to separate string in the stored procedure?
If you pass the comma separated (any separator) string to store procedure and use in query so must need to spit that string and then you will use it.
Below have example:
DECLARE #str VARCHAR(500) = 'monday,tuesday,thursday'
CREATE TABLE #Temp (tDay VARCHAR(100))
WHILE LEN(#str) > 0
BEGIN
DECLARE #TDay VARCHAR(100)
IF CHARINDEX(',',#str) > 0
SET #TDay = SUBSTRING(#str,0,CHARINDEX(',',#str))
ELSE
BEGIN
SET #TDay = #str
SET #str = ''
END
INSERT INTO #Temp VALUES (#TDay)
SET #str = REPLACE(#str,#TDay + ',' , '')
END
SELECT *
FROM tblx
WHERE days IN (SELECT tDay FROM #Temp)
Try this:
CREATE FUNCTION [dbo].[ufnSplit] (#string NVARCHAR(MAX))
RETURNS #parsedString TABLE (id NVARCHAR(MAX))
AS
BEGIN
DECLARE #separator NCHAR(1)
SET #separator=','
DECLARE #position int
SET #position = 1
SET #string = #string + #separator
WHILE charindex(#separator,#string,#position) <> 0
BEGIN
INSERT into #parsedString
SELECT substring(#string, #position, charindex(#separator,#string,#position) - #position)
SET #position = charindex(#separator,#string,#position) + 1
END
RETURN
END
Then use this function,
Select *
from tblx
where days IN (SELECT id FROM [dbo].[ufnSplit]('monday,tuesday,thursday'))
try this
CREATE FUNCTION Split
(
#delimited nvarchar(max),
#delimiter nvarchar(100)
) RETURNS #t TABLE
(
-- Id column can be commented out, not required for sql splitting string
id int identity(1,1), -- I use this column for numbering splitted parts
val nvarchar(max)
)
AS
BEGIN
declare #xml xml
set #xml = N'<root><r>' + replace(#delimited,#delimiter,'</r><r>') + '</r></root>'
insert into #t(val)
select
r.value('.','varchar(max)') as item
from #xml.nodes('//root/r') as records(r)
RETURN
END
GO
usage:
select * from tblx where days in (select val from dbo.split('monday,tuesday,thursday',','))
I think you want this
SELECT * FROM tblx where days in ('Monday','Tuesday','Thursday')
you can get it like this:
var a = "monday,tuesday,thursday";
var sql = string.Format("Select * from tblx where days IN ('{0}')", string.Join("','",a.Split(new[] {','})));
I face the same problem, and i try all the way but not get expected solution. Finally i did like follow. Try it hope it will work...
create Function [dbo].[Split]
(
#RowData NVARCHAR(MAX),
#SplitOn NVARCHAR(5)
)
RETURNS #RtnValue TABLE
(
Id INT IDENTITY(1,1),
Data NVARCHAR(100)
)
AS
BEGIN
DECLARE #Cnt INT
SET #Cnt = 1
WHILE (Charindex(#SplitOn,#RowData)>0)
BEGIN
INSERT INTO #RtnValue (data)
SELECT Data = ltrim(rtrim(Substring(#RowData,1,Charindex(#SplitOn,#RowData)-1)))
SET #RowData = Substring(#RowData,Charindex(#SplitOn,#RowData)+1,len(#RowData))
SET #Cnt = #Cnt + 1
END
INSERT INTO #RtnValue (data)
SELECT Data = ltrim(rtrim(#RowData))
RETURN
END
And in the store procedure put the code like that.
select #ActualTarget= count(*) from UpdateVisitDetails where CreatedBy IN (SELECT [DATA] FROM [dbo].[Split](#AllDATS,',' ))
I have same problem. I tried this.. and this was properly run
ALTER FUNCTION [dbo].[Split]
(
#List varchar(max),
#SplitOn nvarchar(5)
)
RETURNS #RtnValue table
(
Id int identity(1,1),
Value nvarchar(max)
)
AS
BEGIN
IF (len(#List) <=0)
Begin
Return
End
While (Charindex(#SplitOn,#List)>0)
Begin
Insert Into #RtnValue (value)
Select
Value = ltrim(rtrim(Substring(#List,1,Charindex(#SplitOn,#List)-1)))
Set #List = Substring(#List,Charindex(#SplitOn,#List)+len(#SplitOn),len(#List))
End
Insert Into #RtnValue (Value)
Select Value = ltrim(rtrim(#List))
Return
END
Run :
SELECT * FROM dbo.Split('Apple,Banana,Mango',',')
Output:

SQLITE multiple table join with a condition

I have these tables:
doodhiya
dhid INTEGER PRIMARY KEY NOT NULL,
dname TEXT NOT NULL,
dfname TEXT NOT NULL,
dage INTEGER NOT NULL,
dadd TEXT,
dphone INTEGER NOT NULL,
demail TEXT NOT NULL
doodhdata
dtid INTEGER PRIMARY KEY NOT NULL,
ddate INTEGER NOT NULL,
dmonth INTEGER NOT NULL,
dyear INTEGER NOT NULL,
dmilk INTEGER NOT NULL,
dprice INTEGER NOT NULL default 35 ,
dmore TEXT,
ddhid INTEGER NOT NULL
pricemilk
pid INTEGER PRIMARY KEY NOT NULL,
pmonth INTEGER NOT NULL,
pyear INTEGER NOT NULL,
milkprice INTEGER NOT NULL,
typeperson TEXT,
userid INTEGER,
gheeprice INTEGER,
defaultprice TEXT
cashdata
cashid INTEGER PRIMARY KEY NOT NULL,
cashdate INTEGER NOT NULL,
cashmonth INTEGER NOT NULL,
cashyear INTEGER NOT NULL,
cashamount INTEGER NOT NULL,
uid INTEGER NOT NULL,
utype TEXT NOT NULL,
cashtype TEXT NOT NULL,
cashmore TEXT
I want to make a monthly bill and I am succeed buy using it... but in a bill how can i show last month balance....I am trying to use it
SELECT
ddhid, dmonth, dyear, dmilk,
userid, pmonth, pyear, milkprice,
uid, cashmonth, cashyear, cashamount, utype,
SUM(dmilk) AS totalmilk,
SUM(dmilk*milkprice) AS totalamount,
SUM(cashamount) AS totalcash
FROM
doodhdata
LEFT JOIN pricemilk ON (
doodhdata.ddhid = pricemilk.userid
AND doodhdata.dmonth = pricemilk.pmonth
AND doodhdata.dyear = pricemilk.pyear
)
LEFT JOIN cashdata ON (
doodhdata.ddhid = cashdata.uid
AND doodhdata.dmonth = cashdata.cashmonth
AND doodhdata.dyear = cashdata.cashyear
)
WHERE
dmonth > '$mikdatem'
AND dyear='$mikdatey'
AND ddhid='$dhid'
But I want to use defaultprice when milkprice is NULL....how it is possible...?
Use
COALESCE(milkprice, defaultprice)
in place of milkprice in your query.
See SQLite core functions documentation.

Resources