postgres varchar needs casting - sql

I have 2 tables in 2 different schemas scha schb (e.g) and in scha I have a several tables that are all made of varchar as I had to format some data [it was part of the task]
now I have the same tables but with different types in schb.
The problem is this, Wherever I have a type which involves numbers (money, numerical, date), it's giving me an error to CAST.
Is there a way where I can CAST, without the need of copying one coloumn after another (copying it all in one go)
for example
INSERT INTO schb.customer
SELECT "col1", "col2" "col3 **(needs casting)**...."
FROM scha.customer
Thanks

A SELECT clause is not a list of columns, it is a list of expressions (which usually involve columns). A type cast is an expression so you can put them right into your SELECT. PostgreSQL supports two casting syntaxes:
CAST ( expression AS type )
expression::type
The first is standard SQL, the :: form is PostgreSQL-specific. If your schb.customer.col3 is (for example) numeric(5,2), then you'd say:
INSERT INTO schb.customer (col1, col2, col3)
SELECT col1, col2, cast(col3 as numeric(5,2))
FROM scha.customer
-- or
INSERT INTO schb.customer (col1, col2, col3)
SELECT col1, col2, col3::numeric(5,2)
FROM scha.customer
Note that I've included the column list in the INSERT as well. You don't have to do that but it is a good idea as you don't have to worry about the column order and it makes it easy to skip columns (or let columns assume their default values with explicitly telling them to).

Related

rename columns in a view Oracle

we have a view let's say table1_v
if I run select * from table1_v ,I get an output with a column - Year (Jahr)
I want to know what is the underlying sql so I can find it in Sql developer under details of this view or in all_views.
I wonder because the sql looks like this
select year from table1. such sql will give my the column name YEAR and not Year (Jahr)
I would expect something like this in the view definition -
select year as "Year (Jahr)" from table1
so my question is,where could the column name be renamed if not in the view definition and if it is best practice?
If you do want to rename it in the view then give the column an alias:
CREATE VIEW view_name (col1, col2, col3, col4, "Year (Jahr)", col6, col7) AS
SELECT col1, col2, col3, col4, year, col5, col6
FROM table_name;
However, don't, as it is not best-practice.
If you want to include mixed-case, spaces and symbol characters in your identifiers then you will need to use a quoted identifier and that means you would need to use the exact same quoted identifier wherever it is reused in queries. Because of the difficulties caused by matching cases, etc. using quoted identifiers is not considered best-practice and you should use unquoted identifiers wherever possible.
Where could the column name be renamed if not in the view definition and if it is best practice?
Instead of changing the view, you can alias the column when you SELECT from the view when you want to display the output:
SELECT col1, col2, col3, col4, year AS "Year (Jahr)", col6, col7
FROM view_name;

Problem with the integer value in an SQL syntax: #1366 error

I was making a php website with some forms that let you make a form which let's you make an account, but for some reason when I was checking the SQL I was using inside phpmyadmin...
The SQL code it gave me an error that of
#1366 Incorrect integer value
Here is the SQL code I was checking:
INSERT INTO Users VALUES ('','$username','$password','0','empty')
The weird thing about this is the fact that the integer ID, which is in auto-increment, as I've learned it should be blank in the syntax like I've done (the ID column is the first one in my table)
When you are inserting rows into a table, the best practice is to always list the columns:
INSERT INTO Users (col1, col2, col3, col4)
VALUES ('', '$username', '$password', '0', 'empty');
I don't know what your column names are, so you have to fill them in.
If you are writing application code, another best practice is to use proper parameters rather than munging a query string with values.

SQL Server: Inserting from various sources

The simple version
What is the correct syntax of this?
INSERT INTO foo(IP, referer)
VALUES(SELECT bin FROM dbo.bar("foobar"),"www.foobar.com/test/")
I am getting syntax errors near 'SELECT' and ')'
The long version: I want to insert using a Function and a string (this is simplified, in reality there will be a few other values including datetime, ints, etc to insert along with the function result).
I have a function, itvfBinaryIPv4, which was set up to convert IPs to a binary(4) datatype to allow for easy indexing, I used this as a reference: Datatype for storing ip address in SQL Server.
So this is what I am trying to accomplish:
INSERT INTO foo (IP, referer)
VALUES(SELECT bin FROM dbo.itvfBinaryIPv4("192.65.68.201"), "www.foobar.com/test/")
However, I get syntax errors near 'SELECT' and ')'. What is the correct syntax to insert with function results and direct data?
It should be like this -
INSERT INTO foo (IP, referer)
SELECT bin, 'www.foobar.com/test/'
FROM dbo.itvfBinaryIPv4('192.65.68.201')
here assume dbo.itvfBinaryIPv4("192.65.68.201") is table valued function.
The INSERT command comes in two flavors:
(1) either you have all your values available, as literals or SQL Server variables - in that case, you can use the INSERT .. VALUES() approach:
INSERT INTO dbo.YourTable(Col1, Col2, ...., ColN)
VALUES(Value1, Value2, #Variable3, #Variable4, ...., ValueN)
Note: I would recommend to always explicitly specify the list of column to insert data into - that way, you won't have any nasty surprises if suddenly your table has an extra column, or if your tables has an IDENTITY or computed column. Yes - it's a tiny bit more work - once - but then you have your INSERT statement as solid as it can be and you won't have to constantly fiddle around with it if your table changes.
(2) if you don't have all your values as literals and/or variables, but instead you want to rely on another table, multiple tables, or views, to provide the values, then you can use the INSERT ... SELECT ... approach:
INSERT INTO dbo.YourTable(Col1, Col2, ...., ColN)
SELECT
SourceColumn1, SourceColumn2, #Variable3, #Variable4, ...., SourceColumnN
FROM
dbo.YourProvidingTableOrView
Here, you must define exactly as many items in the SELECT as your INSERT expects - and those can be columns from the table(s) (or view(s)), or those can be literals or variables. Again: explicitly provide the list of columns to insert into - see above.
You can use one or the other - but you cannot mix the two - you cannot use VALUES(...) and then have a SELECT query in the middle of your list of values - pick one of the two - stick with it.
Haven't checked it, but the correct syntax would be:
INSERT INTO foo (IP, referer)
SELECT bin, "www.foobar.com/test/" FROM dbo.itvfBinaryIPv4("192.65.68.201")

oracle get current date along with data from table

I'm unable to find such example in the web. I'm not an oracle user (I've been using mysql). As I read in the web, you shall use "FROM DUAL" in Oracle, when the data is not fetched from a real table (a function, for example). But how what can I do when I want to attach current date, e.g. SYSDATE when retrieving some real table data?
Let's say I've got an A table with col1 and col2 columns. Is any of the following correct? If not, please write a correct one:
SELECT col1, col2, SYSDATE
FROM A;
SELECT col1, col2, TO_CHAR(SYSDATE, 'MM-DD-YYYY HH24:MI:SS')
FROM A;
SELECT col1, col2, TRUNC(SYSDATE)
FROM A;
SELECT col1, col2, TRUNC(SYSDATE)
FROM A, DUAL;
Unfortunately, I don't have an oracle installation to test this... that's why I write it here.
This is a bit long for a comment.
They all look correct to me. The fourth uses comma in the from clause. I encourage you to never use commas in the from clause. Instead, always use explicit join syntax, replacing the comma with a cross join. However, the use of dual is pretty useless in that particular query.
You should learn about SQL Fiddle (www.sqlfiddle.com). This is a place where you can try out your code on several different databases.

Select (column-name) as subquery [duplicate]

This question already has answers here:
SQL column names and comparing them to row records in another table in PostgreSQL
(3 answers)
Closed 9 years ago.
I am trying to have a SQL statement where the column names in the SELECT are a subquery. The basic format is:
SELECT (<subquery for columns>) FROM Table;
My subquery returns 4 rows of field names, so I need to make them a single row. I used:
SELECT array_to_string(array_agg(column_names::text),',') FROM Fieldnames;
And then I get a returned format of col1, col2, col3, col4 for my 4 returned rows as a string. If I paste in the raw test for my query, it works fine as:
SELECT (col1, col2, col3, col4) FROM Table;
The issue arises when I put the two together. I get an odd response from psql. I get a:
?column?
col1, col2, col3, col4
with no rows returned for:
SELECT(SELECT array_to_string(array_agg(column_names::text),',') FROM Fieldnames) FROM Table;
Conceptually, I think there are two ways I can address this. I need to get my subquery SELECT back in a format that I can put as the column-name argument to the first SELECT statement, but because I return multiple rows (of a single value of a varchar for the column name that I want), I thought I could just paste them together but I cannot. I am using psql so I do not have the "#" list trick.
Any advice would be appreciated.
Solution:
Here is why the question is not a duplicate, and how I solved it. In trying to simplify the question to be manageable, it lost its muster. I ended up writing a function because I couldn't use # to pass a list to SELECT in PostgreSQL. When you want to select only a subset of rows, you cannot pass a nested (SELECT) even with an AS, although this works in Oracle. As a result, I wrote a function that effective created a string, and then passed it as the SELECT. There seems to be something fundamentally different on how the SQL parser in PostgreSQL handles the arguments for SELECT from Oracle, but everyone DB is different.
If you enclose several column names in parentheses like you do:
SELECT (col1, col2, col3, col4) FROM tbl;
.. you effectively create an ad-hoc row type from the enclosed columns, which has no name, because you did not provide an alias. Postgres will choose a fallback like ?column?. In later Postgres versions the default name is row since, internally, the above is short syntax for:
SELECT ROW(col1, col2, col3, col4) FROM tbl;
Provide your own name (alias):
SELECT (col1, col2, col3, col4) AS my_row_type FROM tbl;
But you probably just want individual columns. Drop the parentheses:
SELECT col1, col2, col3, col4 FROM tbl;