Use Expression Result (e.g. Month) as Column Name in SQL Express - date

I'm writing an SQL expression and I'd like to use the current month as the column name/header.
Code:
Select MONTH(GETDATE()) AS MONTH(GETDATE())
FROM SomeTable;
Error:
Error 102: Incorrect syntax near 'GETDATE'.
This is for a school project and I'm not sure if it's possible. If it is, I'd like to possibly convert that Month number to the actual month name. Thanks in advance.
Oh, and I'm using LinqPad to test the queries on a remote DB and SQL Express Server (Transact-SQL).
Cheers,
Lindsay

I think, You can not use function in column alias, if you try to then you get this error incorrect syntex "Expecting ID, QUOTED_ID, STRING, or TEXT_LEX" which means the alias text has to be hard coded.
I would suggest, you use your front end application to set current month as header, instead of relying on back end sql query.

The alias for your computed columns shouldn't contain any function - just text:
SELECT
MONTH(GETDATE()) AS 'Month'
FROM
dbo.SomeTable

Related

Azure data factory: pass where clause as a string to dynamic query with quotes

I have a Lookup that retrieves a few records from a MS SQL table containing schema, table name and a whole where clause. These values are passed to a copy data (within a ForEach) In the copy data i use a Dynamic query statement like:
#concat('select a.*, current_date as crt_tms from ',item().shm_nam,'.',item().tab_nam,
item().where_clause )
This construction works fine without the where_clause or with a where clause with an integer. But it goes wrong with strings like:
'a where a.CODSYSBRN ='XXX' ;'
it's about the quote (')
How can i pass it through?
I know that the where clause as a fixed string in the dynamic query works when i use double quotes (to escape the single quote):
'a where a.CODSYSBRN =''XXX'' ;'
Point is i need the where clause to be completely dynamic because it differ per table
whatever i try i get this kind of error:
Syntax error or access violation;257 sql syntax error: incorrect syntax near "where a"
ps i also tested this, but with the same result:
select a.*, current_date as crt_tms from #{item().shm_nam}.#{item().tab_nam} a #{item().where_clause}
As you have mentioned you are getting whole where clause from the lookup table, the query must have included the column values in where clause for string and integer types separately.
Example lookup table:
In your copy activity, you can use Concat() function as you were already doing it, to combine static values & parameters.
#concat('select * from ',item().schma_name,'.',item().table_name,' ',item().where_clause)
For debugging purposes, I have added the expression in set variable activity, to see the value of the expression.
Iteration1:
Iteration2:

Using xmlserialize in db2 with a timestamp

I was looking for a way to combine multiple returned rows into a single row on a db2 database (I have an application that can query a database, but will only work if a single row is returned). I found this solution which worked pretty well and was a lot easier than using recursive SQL. However, I ran into a problem when I tried to include a column that was set as TIMESTAMP instead of VARCHAR.
So how can I make this work if a column is a TIMESTAMP type?
Error:
SQL0440N No authorized routine named "XMLTEXT" of type "FUNCTION" having
compatible arguments was found. SQLSTATE=42884
SQL0440N No authorized routine named "XMLTEXT" of type "FUNCTION " having compatible arguments was found.
".
Example:
select xmlserialize(
xmlagg(
xmlconcat(
xmltext(column_name),
xmltext(':'),
xmltext(content),
xmltext(','),
xmltext(DATETIMESTAMP),
xmltext(',')
)
) as varchar(10000)
)
from
yourtable
Instead of the suggested CAST you could wrap the TOCHAR` function around the timestamp value:
select xmlserialize(
xmlagg(
xmlconcat(
xmltext(column_name),
xmltext(':'),
xmltext(content),
xmltext(','),
xmltext(TO_CHAR(DATETIMESTAMP)),
xmltext(',')
)
) as varchar(10000)
)
from
yourtable
If you are on a recent version of DB2 and have LISTAGG available I would recommend to use that function. It is much faster than converting the SQL input to XML types and then converting it back. It requires some CPU cycles due to all the official rules involved.

Error catching a function error in TSQL

I am working with a SQL Server 2005 database table that is currently storing dates as varchars. This is outside of my control. For ease of reporting, I would like to create a view that converts these varchar dates to datetime fields.
The varchar dates are formatted for the most part, except for the occasional typing error.
DateString
----------
2001/01/02 -- most of the fields
2002/0601 -- typo, missing slash between month and day
2004/02/30 -- typo, no 30th of February
Because the dates are already formatted, I'm using the cast function to convert them to datetime.
cast(DateString as datetime)
The problem is when the cast function comes across an incorrect date, the query ends in error.
Is there are way to wrap just the function in a try...catch block? I see it is possible to wrap an entire query in a try...catch block, but the full query has multiple casts that must be done, and any combination could have typing errors.
I would use the built-in ISDATE() function. You can then write a CASE statement within your SELECT statement to either return the parsed date or either a null or some other result. Or, you can place it directly in the WHERE clause to only return those rows where there is a valid date.
A possible solution with the ISDATE() function in the SELECT list may look like:
select case
when ISDATE(DateString) = 1 then cast(DateString as datetime)
else null --or other error result
end as CastedDate
from TableName
If the logic is complicated (e.g. you want to try to correct the errors, such as missing slash, or nearest day in the case of 30th FEB), then one option is to create a user-defined function that contains the date parsing logic (string to date) logic in it, complete with error handling (e.g. scenario checking before casting). Then in the query, call the user defined function.
An outline:
CREATE FUNCTION udf_ParseDateString
(
#DateString nvarchar(20)
)
RETURNS DateTime
AS
BEGIN
DECLARE #returnDateTime datetime
-- Do any string checking, and date casting here
-- #DateString -> #returnDateTime
return #returnDateTime
END
Note that you won't be able to use TRY-CATCH in a UDF.
Alternatively, if your logic is simple, you could just use a cast inline, as suggested here.
SET DATEFORMAT ymd;
-- Incorporate this into query.
SELECT CASE WHEN ISDATE(#yourParameter) = 1
THEN CAST(#yourParameter AS DATETIME)
ELSE YourDefaultValue
END
If you were using SQL Server 2012, you could use the TRY_CAST function.

Multiple SQL queries in a report

The requirement is to generate a single report connecting to a single DB:
Query1 is a group by query and has a bar chart and pie chart based on it.
Query2 is a simple query on which a table gets created.
Both these queries need results based on a WHERE clause, which is supplied dynamically.
Can somebody point me to some examples on how to achieve this?
Thank you.
You can tell JasperReports to use a parameter to define part of the query using the $P!{PARAMETER_NAME} syntax. This tells JasperReports to use the literal value of PARAMETER_NAME as part of the query. You can then do:
Create a parameter named WHERE_CLAUSE in the report.
Give WHERE_CLAUSE a default value of 1=1.
Consider the following SQL statement:
SELECT * FROM table WHERE $P!{WHERE_CLAUSE}
The $P! expression changes the literal SQL statement to:
SELECT * FROM table WHERE 1=1
That is a valid query. Note the difference between $P{} and $P!{} -- the exclamation mark (!) is important.
You can then supply the SQL conditions dynamically.

make a column in sybase default to the current date/time of row insertion

I have a sybase 15 DB and for one of my tables, I want to make a column default to the current date/time of the row insert. Is this possible?
In a sybase text, the following is said:
ALTER TABLE sales_order
MODIFY order_date DEFAULT CURRENT DATE
On my DB this doesn't do anything, as CURRENT DATE is not recognized.
using getDate() is a valid solution, you must have had a syntax error. Try it like this:
create table test_tbl (
date_data DATETIME default getDate() NOT NULL
)
Try using getDate() instead
... DEFAULT GETDATE() is correct. the case is irrelevant; mixed case may indicate a Java method, but it is a straight TSQL Function. Please post the exact error msg if you want further assistance.
Also, the ALTER TABLE method sets the Default for future INSERTS; if you want the existing data changed, you need to UPDATE (good for small tables) or unload/reload the table (demanded for the large).
Watch the NULL/NOT NULL: you do not want to change that without understanding. Again, the existing/future issue needs address. NOT NULL prevents NULL being explicitly passed as an INSERT VALUE.
CURRENT_DATE is a SQL standard that isn't universally adopted.
As noted elsewhere the getdate() T-SQL function should be used instead.