Skip to content

Conversation

@mnsrulz
Copy link
Contributor

@mnsrulz mnsrulz commented Mar 6, 2022

this is in continuation of supporting cross apply addressed in #541

With this PR one can put where clause when there is no table to select

SELECT 1 WHERE 1=1

@ahmad-moussawi
Copy link
Contributor

While there is no restriction to merge this, just curious to know the use case for it :)

@mnsrulz
Copy link
Contributor Author

mnsrulz commented Mar 9, 2022

Consider the following query

var q = new Query("Users as U")
    .Select("U.{UserId,Name}")
    .LeftJoin("UserAttributes as UA", "U.UserId", "UA.UserId")
    .Join(new Query().As("O1").SelectRaw("1 AS C1")
        .WhereNotNull("UA.UserId"), j => j, "outer apply")
    .LeftJoin("UserAttributes2 as UA2", "U.UserId", "UA2.UserId")
    .Join(new Query().As("O2").SelectRaw("1 AS C2")
        .WhereNotNull("UA2.UserId")
        .WhereNotNull("C1"), j => j, "outer apply");

generates

SELECT [U].[UserId], [U].[Name] FROM [Users] AS [U] 
LEFT JOIN [UserAttributes] AS [UA] ON [U].[UserId] = [UA].[UserId]
OUTER APPLY (SELECT 1 AS C1) AS [O1]
LEFT JOIN [UserAttributes2] AS [UA2] ON [U].[UserId] = [UA2].[UserId]
OUTER APPLY (SELECT 1 AS C2) AS [O2]

Please notice the where clause in the outer apply select query, missing the where clauses. I can make a workaround by applying a join clause like

.Join(new Query().As("O1").SelectRaw("1 AS C1")
        .WhereNotNull("UA.UserId"), j => j.WhereNotNull("UA.UserId"), "outer apply")

which could possibly give the desired result from sql result perspective,
OUTER APPLY (SELECT 1 AS C1) AS [O1] ON ([UA].[UserId] IS NOT NULL)

however, the Where clause in the outer apply select should honor the where clause and produce the result as below

OUTER APPLY (SELECT 1 AS C1 WHERE [UA].[UserId] IS NOT NULL) AS [O1]

@ahmad-moussawi
Copy link
Contributor

Thanks @mnsrulz very valid reason.

@ahmad-moussawi ahmad-moussawi merged commit 10536d8 into sqlkata:master Mar 9, 2022
@ahmad-moussawi
Copy link
Contributor

@all-contributors please add @mnsrulz for code

@allcontributors
Copy link
Contributor

@ahmad-moussawi

I've put up a pull request to add @mnsrulz! 🎉

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants