i want to trim trailing spaces for teradata table columns,
i do it like this,
trim(trailing from dictionary_managed_databases.dbname),
or use trim directly,
trim(dictionary_managed_databases.dbname),
but the result shows:
seems the trim do not work,
not sure how to do it in teradata,
create volatile table test ( dbname varchar(128) CHARACTER SET UNICODE ) on commit preserve rows;
insert into test values ( 'Database-Name' );
-- you don't need to trim a varchar column
select dbname || '~' from test;
(dbname||'~')
---------------------------------------------------------------------------------------------------------------------------------
Database-Name~
-- it is always max length, so not to loose any possible content
select trim(dbname) || '~' from test;
(Trim(BOTH FROM dbname)||'~')
---------------------------------------------------------------------------------------------------------------------------------
Database-Name~
-- you may cast it to shorten the resulting column
select cast(trim(dbname) as varchar(30)) from test;
Trim(BOTH FROM dbname)
------------------------------
Database-Name
-- it will never be less then the header, even if the content is less
select cast(trim(dbname) as varchar(10)) from test;
Trim(BOTH FROM dbname)
----------------------
Database-N
-- but it will truncate the result
select cast(trim(dbname) as varchar(10)) as dbname from test;
dbname
----------
Database-N
sel
dictionary_object_map.moId,
trim(dictionary_managed_databases.dbname)|| '~',
dictionary_deployed_info.dictionaryId,
dictionary_deployed_info.dictionaryName,
dictionary_managed_objects.moname
from dictionary_object_map,
dictionary_deployed_info,
dictionary_managed_objects ,
dictionary_managed_databases
where
dictionary_object_map.dictionaryId=dictionary_deployed_info.dictionaryId
and dictionary_object_map.moid=dictionary_managed_objects.moid
and dictionary_managed_databases.moDBId=dictionary_managed_objects.moDBId
and dictionary_managed_databases.dbname = 'customerservice';
the result
don't understand why output of field dbname still look like this,
Related
I am trying to run the below sql by liquibase and I am getting an error expected something between "TABLE" and the keyword "IF" keyword .This is for teradata database
CREATE MULTISET TABLE IF NOT EXISTS SCHEMA_NAME.TABLE_NAME, NO, FALLBACK,
NO BEFORE JOURNAL,
NO AFTER JOURNAL,
CHECKSUM = DEFAULT,
DEFAULT MERGEBLOCKRATIO AS ( I TRIED WITHOUT "AS")
(
COL1 INTEGER,
COL1 INTEGER....ETC)
PRIMARY INDEX( COL1,COL2);
REPLACE PROCEDURE <database_name>.drop_if_exists( in_object varchar(50)) begin IF EXISTS(
SELECT 1
FROM dbc.tables
WHERE tablename = in_object
and databasename='<database_name>') THEN
CALL DBC.SysExecSQL('DROP TABLE ' || in_object);
END IF; END;
Followed by the regular create table statment.
I am very new to Oracle 11g and am trying to generate a large string by appending text for each column in a select statement and using a cursor to store the results. However I want the last statement to not have a union all included. The final result I want to build large string of each row generated or simply execute the result if possible.
Note: column1 has a list of schemas that I am interested in.
select 'select * from ' || column1 || '.' || column2 || ' union all ' from mytable
This is where column1 is the schema, column2 is the table name.
What is the simplest way to generate the final string without using rtrim to remove the last string. And is there a simple way to append all these rows together in the string automatically?
The final goal is to actually just execute the union into a resulting cursor.
If you're querying in a loop anyway I wouldn't try to construct the string as part of the select at all; I'd do it all within the loop. Something like (untested):
declare
str varchar2(32768);
begin
for rec in (select column1, column2, rownum as rn from mytable)
loop
if rec.rn > 1 then
str := str || ' union all ';
end if;
str := str || 'select * from "' || rec.column[ || '"."' || rec.column2 ||'"';
end loop;
-- do something with str e.g. display to verify the syntax
-- before using in a cursor
dbms_output.put_line(str);
end;
Rather than adding union all to the end of every row except the last one,the rn check means it's added to the start of every row except the first one, which is easier to detect.
I've also wrapped the schema and table names in double quotes, just in case you have to deal with any quoted identifiers. But if your stored values don't match the case of the owners and table names in all_tables this will cause a problem rather than solve it.
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))
I am writing an SQL query in which that I will need to perform a sub select on a table, which will usually return multiple rows. I need to be able to join together the results of a certain field from all the rows into one field to output. Is this possible, and how?
For example, if the SQL query returns
id | field
1 | test1
2 | test2
3 | test3
I need the outputted field to be "test1 test2 test3".
Thanks
Here's the for xml trick to do that:
SELECT field + ' ' as [text()]
FROM YourTable
FOR XML PATH ('')
This prints:
test1 test2 test3
It's typically used with an outer apply to execute it once for each row.
declare #sample table(id int, field varchar(20))
insert into #sample values(1,'test1')
insert into #sample values(2,'test2')
insert into #sample values(3,'test3')
declare #result varchar(max) set #result = ''
select #result = #result + ' '+field from #sample
select #result
A SQLCLR custom aggregator would be a an alternative (read better) solution
Try this:
SELECT RTRIM(field)
FROM (
SELECT field + ' ' field
FROM <YOUR_TABLE>
FOR XML PATH('')
) a
As an addition to the existing answers. Try including the COALESCE expression with column name your going to use. This avoids having null values in your concatenated string and avoid your list looking like this. Notice the redundant blank space.
field1 field2 field4 field
Further details can be found here.
GO
DECLARE #tableName VARCHAR(MAX)
SELECT #tableName = COALESCE(#tableName + ' ' ,'') + Name
FROM sys.tables
SELECT #tableName
GO
it is possible to do with a cursor.
declare #field nvarchar(max)
declare #concat nvarchar(max)
set #concat = ''
declare #cursor cursor
set #cursor = cursor for select field from table
open #cursor
fetch next from #cursor into #field
while ##fetch_status = 0
begin
set #concat = concat(#concat,#field)
fetch next from #cursor into #field
end
your exercise is to add space between the concatenated strings :-)
I am looking to retrieve a list of columns in a table. The database is the latest release of SQLite (3.6, I believe). I am looking for code that does this with a SQL query. Extra bonus points for metadata related to the columns (e.g. length, data type, etc...)
What you're looking for is called the data dictionary. In sqlite a list of all tables can be found by querying sqlite_master table (or view?)
sqlite> create table people (first_name varchar, last_name varchar, email_address varchar);
sqlite> select * from sqlite_master;
table|people|people|2|CREATE TABLE people (first_name varchar, last_name varchar, email_address varchar)
To get column information you can use the pragma table_info(table_name) statement:
sqlite> pragma table_info(people);
0|first_name|varchar|0||0
1|last_name|varchar|0||0
2|email_address|varchar|0||0
For more information on the pragma statements, see the documentation.
Here's the simple way:
.schema <table>
The question is old but the following hasn't been mentioned yet.
Another convenient way in many cases is to turn headers on by:
sqlite> .headers on
Then,
sqlite> SELECT ... FROM table
will display a headline showing all selected fields (all if you SELECT *) at the top of the output.
Here's a SELECT statement that lists all tables and columns in the current database:
SELECT m.name as tableName,
p.name as columnName
FROM sqlite_master m
left outer join pragma_table_info((m.name)) p
on m.name <> p.name
order by tableName, columnName
;
just go into your sqlite shell:
$ sqlite3 path/to/db.sqlite3
and then just hit
sqlite> .schema
and you will get everything.
This is a query that lists all tables with their columns, and all the metadata I could get about each column as OP requested (as bonus points).
SELECT
m.name AS table_name,
p.cid AS col_id,
p.name AS col_name,
p.type AS col_type,
p.pk AS col_is_pk,
p.dflt_value AS col_default_val,
p.[notnull] AS col_is_not_null
FROM sqlite_master m
LEFT OUTER JOIN pragma_table_info((m.name)) p
ON m.name <> p.name
WHERE m.type = 'table'
ORDER BY table_name, col_id
Thanks to #David Garoutte for showing me how to get pragma_table_info to work in a query.
Run this query to see all the table metadata:
SELECT * FROM sqlite_master WHERE type = 'table'
Building on the above, you can do it all at once:
sqlite3 yourdb.db ".schema"
That will give you the SQL to create the table, which is effectively a list of the columns.
In case if you want to get all column names into one single comma separated string, you can use below.
SELECT GROUP_CONCAT(NAME,',') FROM PRAGMA_TABLE_INFO('table_name')
Here the pragma table_info is used as pragma_table_info for the select statement and GROUP_CONCAT is to combine all the field names into one string. for the second parameter of GROUP_CONCAT you can pass the separator.
I know, it’s been a long time but it’s never too late…
I had a similar question with TCL as interpreter and after several search, found nothing good for me. So I propose something based on PRAGMA, knowing that your DB is “main”
db eval { PRAGMA main.table_info(<your table name>) } TBL { puts $TBL(name) }
And array use to obtain a list
set col_list {}
db eval { PRAGMA main.table_info(<your table name>) } TBL { lappend col_list $TBL(name) }
puts $col_list