Very quick select statement in AX2012 - select

What's your method of quickly viewing results of such statements?
SELECT * FROM CustInvoiceJour`
JOIN CustInvoiceTrans WHERE CustInvoiceJour.InvoiceId == CustInvoiceTrans.InvoiceId`
WHERE CustInvoiceTrans.ItemId == 'MBIIRKT0014'
I'm looking for something like table explorer, but supporting joins.

If this is just for quick data checks, I just usually use info(strFmt(...)); statements to output what I need to see.
Another way, if you're stronger in SQL is to actually use SQL. You can use the keywords generateonly and forceLiterals to generate the SQL statement and force literal values.
Here is your AX SQL statement rewritten:
SELECT generateonly forceLiterals * FROM CustInvoiceJour
JOIN CustInvoiceTrans
WHERE CustInvoiceJour.InvoiceId == CustInvoiceTrans.InvoiceId &&
CustInvoiceTrans.ItemId == 'MBIIRKT0014';
info(CustInvoiceJour.getSQLStatement());
Then you can run that SQL in SQL and do what you need.
Your X++ select has two WHERE's in it and is malformed, but I fixed it.

If you need to make joins In my case I create a simple View object.
Table CustInvoiceJour principal and then joins to CustInvoiceTrans
Views located in AOT/Data Dictionary/Views

Related

PostgreSQL, allow to filter by not existing fields

I'm using a PostgreSQL with a Go driver. Sometimes I need to query not existing fields, just to check - maybe something exists in a DB. Before querying I can't tell whether that field exists. Example:
where size=10 or length=10
By default I get an error column "length" does not exist, however, the size column could exist and I could get some results.
Is it possible to handle such cases to return what is possible?
EDIT:
Yes, I could get all the existing columns first. But the initial queries can be rather complex and not created by me directly, I can only modify them.
That means the query can be simple like the previous example and can be much more complex like this:
WHERE size=10 OR (length=10 AND n='example') OR (c BETWEEN 1 and 5 AND p='Mars')
If missing columns are length and c - does that mean I have to parse the SQL, split it by OR (or other operators), check every part of the query, then remove any part with missing columns - and in the end to generate a new SQL query?
Any easier way?
I would try to check within information schema first
"select column_name from INFORMATION_SCHEMA.COLUMNS where table_name ='table_name';"
And then based on result do query
Why don't you get a list of columns that are in the table first? Like this
select column_name
from information_schema.columns
where table_name = 'table_name' and (column_name = 'size' or column_name = 'length');
The result will be the columns that exist.
There is no way to do what you want, except for constructing an SQL string from the list of available columns, which can be got by querying information_schema.columns.
SQL statements are parsed before they are executed, and there is no conditional compilation or no short-circuiting, so you get an error if a non-existing column is referenced.

Why is SELECT without columns valid

I accidently wrote a query like select from my_table; and surprisingly it is valid statement. Even more interesting to me is that even SELECT; is a valid query in PostgreSQL. You can try to write a lot funny queries with this:
select union all select;
with t as (select) select;
select from (select) a, (select) b;
select where exists (select);
create table a (b int); with t as (select) insert into a (select from t);
Is this a consequence of some definition SQL standard, or there is some use case for it, or it is just funny behavior that no one cared to programatically restrict?
Right from the manual:
The list of output expressions after SELECT can be empty, producing a zero-column result table. This is not valid syntax according to the SQL standard. PostgreSQL allows it to be consistent with allowing zero-column tables. However, an empty list is not allowed when DISTINCT is used.
The possibility of "zero-column" tables is a side effect of the table inheritance if I'm not mistaken. There were discussions over this on the Postgres mailing lists (but I can't find them right now)

SQL Views - no variables?

Is it possible to declare a variable within a View? For example:
Declare #SomeVar varchar(8) = 'something'
gives me the syntax error:
Incorrect syntax near the keyword 'Declare'.
You are correct. Local variables are not allowed in a VIEW.
You can set a local variable in a table valued function, which returns a result set (like a view does.)
http://msdn.microsoft.com/en-us/library/ms191165.aspx
e.g.
CREATE FUNCTION dbo.udf_foo()
RETURNS #ret TABLE (col INT)
AS
BEGIN
DECLARE #myvar INT;
SELECT #myvar = 1;
INSERT INTO #ret SELECT #myvar;
RETURN;
END;
GO
SELECT * FROM dbo.udf_foo();
GO
You could use WITH to define your expressions. Then do a simple Sub-SELECT to access those definitions.
CREATE VIEW MyView
AS
WITH MyVars (SomeVar, Var2)
AS (
SELECT
'something' AS 'SomeVar',
123 AS 'Var2'
)
SELECT *
FROM MyTable
WHERE x = (SELECT SomeVar FROM MyVars)
EDIT: I tried using a CTE on my previous answer which was incorrect, as pointed out by #bummi. This option should work instead:
Here's one option using a CROSS APPLY, to kind of work around this problem:
SELECT st.Value, Constants.CONSTANT_ONE, Constants.CONSTANT_TWO
FROM SomeTable st
CROSS APPLY (
SELECT 'Value1' AS CONSTANT_ONE,
'Value2' AS CONSTANT_TWO
) Constants
#datenstation had the correct concept. Here is a working example that uses CTE to cache variable's names:
CREATE VIEW vwImportant_Users AS
WITH params AS (
SELECT
varType='%Admin%',
varMinStatus=1)
SELECT status, name
FROM sys.sysusers, params
WHERE status > varMinStatus OR name LIKE varType
SELECT * FROM vwImportant_Users
also via JOIN
WITH params AS ( SELECT varType='%Admin%', varMinStatus=1)
SELECT status, name
FROM sys.sysusers INNER JOIN params ON 1=1
WHERE status > varMinStatus OR name LIKE varType
also via CROSS APPLY
WITH params AS ( SELECT varType='%Admin%', varMinStatus=1)
SELECT status, name
FROM sys.sysusers CROSS APPLY params
WHERE status > varMinStatus OR name LIKE varType
Yes this is correct, you can't have variables in views
(there are other restrictions too).
Views can be used for cases where the result can be replaced with a select statement.
Using functions as spencer7593 mentioned is a correct approach for dynamic data. For static data, a more performant approach which is consistent with SQL data design (versus the anti-pattern of writting massive procedural code in sprocs) is to create a separate table with the static values and join to it. This is extremely beneficial from a performace perspective since the SQL Engine can build effective execution plans around a JOIN, and you have the potential to add indexes as well if needed.
The disadvantage of using functions (or any inline calculated values) is the callout happens for every potential row returned, which is costly. Why? Because SQL has to first create a full dataset with the calculated values and then apply the WHERE clause to that dataset.
Nine times out of ten you should not need dynamically calculated cell values in your queries. Its much better to figure out what you will need, then design a data model that supports it, and populate that data model with semi-dynamic data (via batch jobs for instance) and use the SQL Engine to do the heavy lifting via standard SQL.
What I do is create a view that performs the same select as the table variable and link that view into the second view. So a view can select from another view. This achieves the same result
How often do you need to refresh the view? I have a similar case where the new data comes once a month; then I have to load it, and during the loading processes I have to create new tables. At that moment I alter my view to consider the changes.
I used as base the information in this other question:
Create View Dynamically & synonyms
In there, it is proposed to do it 2 ways:
using synonyms.
Using dynamic SQL to create view (this is what helped me achieve my result).

Conditional dynamic SQL with cursor

I have a query which uses a cursor to cycle through the results of a select statement.
The select statement in short selects all of the records from a mapping table I have. One of the columns is 'SourceTableName'.
I use this field to generate some dynamic SQL.
I am looking to add a parameter to my stored procedure wrapped around this, which will allow me to only create dynamic SQL for the 'SourceTableName' that I want - IF I pass in a 'SourceTableNameFilter'.
I am stuck with some logic which wraps my dynamic SQL.
IF #SourceTableNameFilter(SP parameter) = #SourceTableName(from mapping table)
BEGIN
Generate and execute some dynamic SQL based on the SourceTableName.
The problem is, I want this to either work on all tables that come back from a select against 'SourceTableName' BUT if a #SourceTableNameFilter parameter is present and not null - then only generate dynamic SQL for any rows in the cursor which match my filter parameter.
Is there a way for me to accomplish this with an IF statement without copying the logic inside the IF/ELSE twice?
FETCH NEXT FROM TABLECUR INTO #SourceTableName
,#SourceInColumn
,#SourceOutColumn
,#TargetTableName
,#TargetLookupColumn
,#TargetLookupResultColumn
,#MappingTableID
WHILE (##fetch_status <> -1)
BEGIN
IF (##fetch_status <> -2)
BEGIN
IF (#SourceTableName = #SourceTableNameFilter)
--GENERATE DYNAMIC SQL
ELSE
--GENERATE DYNAMIC SQL FOR ALL RECORDS
The generate dynamic SQL string is the same in both the if and the else, any way to change the conditions so that I'm not duplicating the dynamic SQL generation and to not generate dynamic SQL when the #SourceTableName != #SourceTableNameFilter?
Thank you
Consider adding this logic to the cursor definition, rather than having that logic within the processing of each cursor record.
So if the cursor is normally:
DECLARE MY_CURSOR Cursor FOR
SELECT SourceTableName, SourceInColumn, SourceOutColumn
,TargetTableName, TargetLookupColumn
,TargetLookupResultColumn, MappingTableID
FROM MappingTable
--get source tables when filter is specified; otherwise get all
WHERE (SourceTableName = #SourceTableNameFilter) OR (LEN(ISNULL(SourceTableNameFilter,'')=0)
Now you can execute your business logic within the cursor without having to detect the filtered table or not. The cursor is loaded with the records you need to care about. It sounds, from the question, that the business logic is the same, no matter if the filter was passed in or not. If this is incorrect, or if it doesn't satisfy your requirement, please comment.
Knowing nothing about the dynamic sql you're building, I'd recommend doing something along the lines of:
SET #DynamicCommand = '<whatever, first part>'
+ isnull(#SourceTableNameFilter
,'<no special action, perhaps just empty string>'
,'<add conditional text dependent upon contents of #SourceTableNameFilter>')
+ '<whatever, second part>'

Is it possible to use CASE with IN?

I'm trying to construct a T-SQL statement with a WHERE clause determined by an input parameter. Something like:
SELECT * FROM table
WHERE id IN
CASE WHEN #param THEN
(1,2,4,5,8)
ELSE
(9,7,3)
END
I've tried all combination of moving the IN, CASE etc around that I can think of. Is this (or something like it) possible?
try this:
SELECT * FROM table
WHERE (#param='??' AND id IN (1,2,4,5,8))
OR (#param!='??' AND id in (9,7,3))
this will have a problem using an index.
The key with a dynamic search conditions is to make sure an index is used, instead of how can I easily reuse code, eliminate duplications in a query, or try to do everything with the same query. Here is a very comprehensive article on how to handle this topic:
Dynamic Search Conditions in T-SQL by Erland Sommarskog
It covers all the issues and methods of trying to write queries with multiple optional search conditions. This main thing you need to be concerned with is not the duplication of code, but the use of an index. If your query fails to use an index, it will preform poorly. There are several techniques that can be used, which may or may not allow an index to be used.
here is the table of contents:
Introduction
The Case Study: Searching Orders
The Northgale Database
Dynamic SQL
Introduction
Using sp_executesql
Using the CLR
Using EXEC()
When Caching Is Not Really What You Want
Static SQL
Introduction
x = #x OR #x IS NULL
Using IF statements
Umachandar's Bag of Tricks
Using Temp Tables
x = #x AND #x IS NOT NULL
Handling Complex Conditions
Hybrid Solutions – Using both Static and Dynamic SQL
Using Views
Using Inline Table Functions
Conclusion
Feedback and Acknowledgements
Revision History
if you are on the proper version of SQL Server 2008, there is an additional technique that can be used, see: Dynamic Search Conditions in T-SQL Version for SQL 2008 (SP1 CU5 and later)
If you are on that proper release of SQL Server 2008, you can just add OPTION (RECOMPILE) to the query and the local variable's value at run time is used for the optimizations.
Consider this, OPTION (RECOMPILE) will take this code (where no index can be used with this mess of ORs):
WHERE
(#search1 IS NULL or Column1=#Search1)
AND (#search2 IS NULL or Column2=#Search2)
AND (#search3 IS NULL or Column3=#Search3)
and optimize it at run time to be (provided that only #Search2 was passed in with a value):
WHERE
Column2=#Search2
and an index can be used (if you have one defined on Column2)
if #param = 'whatever'
select * from tbl where id in (1,2,4,5,8)
else
select * from tbl where id in (9,7,3)