I am looking to pass declared variables to build my string. I think I want to set my variable via a case expression but I have not done this before. Here is what I have done thus far.
DECLARE #stu_conv AS VARCHAR(5)
-- I think I need a select here.
set #stu_conv = CASE WHEN ITMMASTER.STU_0 ='KG' THEN'2.2'END
SELECT
YPRIMAT.YCROPYR_0
,ITMMASTER.TCLCOD_0
,SPRICLIST.DCGVAL_3
,ITMMASTER.TSICOD_2
,ITMMASTER.ACCCOD_0
,(BASPRI_0*#stu_conv) AS ImportstringAS Importstring
FROM LIVE.YPRIMAT
INNER JOIN LIVE.ITMMASTER ON YPRIMAT.ITMREF_0 = ITMMASTER.ITMREF_0
LEFT OUTER JOIN LIVE.SPRICLIST ON ITMMASTER.TCLCOD_0 = SPRICLIST.PLICRI1_0
WHERE SPRICLIST.PLICRD_0 = 'SPL000020'
I don't see the point for using a variable here, and trying to set it outside the query does not make sense, since you most likely want the value to reset for each row.
I would suggest moving the case expression into the query, as follows:
select
y.ycropyr_0,
i.tclcod_0,
s.dcgval_3,
i.tsicod_2,
i.acccod_0,
baspri_0 * case when i.stu_0 = 'KG' then 2.2 else 1 end as importstringas importstring
from live.yprimat y
inner join live.itmmaster i on y.itmref_0 = i.itmref_0
left outer join live.spriclist s on i.tclcod_0 = s.plicri1_0
where s.plicrd_0 = 'SPL000020'
I assumed that you want a value of 1 when stu_0 is not 'KG', but you can change this as needed.
Side note:
I modified your query to use table aliases. This makes the query shorter to write and somehow easier to read
you would need to prefix column baspri_0 with the table it belongs to (as your query is, it is not possible to tell)
I'm not sure why you're declaring a string and then multiplying it, but I would just inline the case (and add a default case?):
,(BASPRI_0 * CASE
WHEN ITMMASTER.STU_0 ='KG'
THEN 2.2
ELSE ???
END) AS Importstring
I'm having a Sql code like as follows
Select a.ItemCode, a.ItemDesc
From fn_BOM_Material_Master('A', #AsOnDate, #RptDate, #BranchID, #CompID)a
Left Outer Join fn_INV_AsOnDate_Stock(#StockDate, #AsOnDate, #RptDate, #BranchID, #CompID, #Finyear)b
On a.ItemCode=b.ItemCode and b.WarehouseCode<>'WAP'
and a.BranchID=b.BranchID and a.CompID=b.COmpID
Where a.ItemNatureCode = 'F' and a.BranchID = #BranchID and a.CompID = #CompID
Group by a.ItemCode, a.ItemDesc
Having sum(b.CBQty)<=0
Here the problem is that im passing an "#ShowZeroStock" value as as bit if the "#ShowZeroStock" value is '1' then Having should not be validated or (i.e: All values from the table should be returned including zero)
So How to change the query based on passed bit value "#ShowZeroStock"
I can Use "If else " condition at the top and remove having in else part, but for a lengthy query i can't do the same.
Is this the logic you want?
Having sum(b.CBQty) <= 0 or #ShowZeroStock = 1
I am new with SQL.
How can I write a query, where the Where condition be dependent on a statement which it will be given from a user?
I have this:
SELECT TablePersdaten.Vorname, TablePersdaten.Nachname, TableBezahlung.Datum, TableBezahlung.BelegNr, TableBezahlung.Betrag, Sum(TableBezahlung.Betrag) AS SummevonBetrag
FROM ((TableTeilnehmer INNER JOIN TablePersdaten ON TableTeilnehmer.IDPersdaten = TablePersdaten.IDPersdaten) INNER JOIN TableKurse ON TableTeilnehmer.IDKurs = TableKurse.IDKurs) INNER JOIN TableBezahlung ON TableTeilnehmer.IDTeilnehmer = TableBezahlung.IDStudent
WHERE TableBezahlung.Datum = "VALUE GIVEN FROM USER"
GROUP BY TablePersdaten.Vorname, TablePersdaten.Nachname, TableBezahlung.Datum, TableBezahlung.BelegNr, TableBezahlung.Betrag
ORDER BY TableBezahlung.Datum;
EDIT: I'm using Access 2013, but I'm coding everything myself with SQL-Code. The values should be given through a form.
Research stored procedures. You can include user input as a parameter and then pass it to a WHERE clause through a declared parameter.
So ideally it would go something like (and beware of the INT part it may have to have a different value that corresponds to table.datum:
CREATE PROCEDURE dbo.Proc1
#parameter1 INT
AS
BEGIN
SELECT TablePersdaten.Vorname, TablePersdaten.Nachname, TableBezahlung.Datum, TableBezahlung.BelegNr, TableBezahlung.Betrag, Sum(TableBezahlung.Betrag) AS SummevonBetrag
FROM ((TableTeilnehmer INNER JOIN TablePersdaten ON TableTeilnehmer.IDPersdaten = TablePersdaten.IDPersdaten) INNER JOIN TableKurse ON TableTeilnehmer.IDKurs = TableKurse.IDKurs) INNER JOIN TableBezahlung ON TableTeilnehmer.IDTeilnehmer = TableBezahlung.IDStudent
WHERE TableBezahlung.Datum = #parameter1
GROUP BY TablePersdaten.Vorname, TablePersdaten.Nachname, TableBezahlung.Datum, TableBezahlung.BelegNr, TableBezahlung.Betrag
ORDER BY TableBezahlung.Datum;
END
And of course execute the procedure after creation:
EXEC dbo.Proc1 '#parameter1value'
If you parameterize the input "VALUE GIVEN FROM USER" that might be what you're after.
...
WHERE TableBezahlung.Datum = &UserValue
...
The single '&' will substitute that value once. If you use '&&', it will substitute that value through the end of your session.
I have a SP that returns quite a lot of data every second and is shown in a grid. I'm now trying to reduce bandwidth and thinking of returning only columns currently shown in my grid.
This is of course simplified and minimized but basically what I had was the following SP:
SELECT
[Animals].[AnimalID] AS [AnimalID],
[Animals].[name] AS [AnimalName],
[Foods].[DisplayName] AS [Food],
[Animals].[Age] AS [AnimalAge],
[Animals].[AmountOfFood] AS [AmountOfFood]
What I’m currently trying is to pass a TVP of the names of the fields (#fields) currently shown on the grid and returning only required fields as such:
SELECT
[Animals].[AnimalID] AS [AnimalID],
[Animals].[name] AS [AnimalName],
CASE
WHEN ('Food' in (select * from #fields))
THEN [Foods].[DisplayName]
END AS [Food],
CASE
WHEN ('AnimalAge' in (select * from #fields))
THEN [Animals].[Age]
END AS [AnimalAge],
CASE
WHEN ('AmountOfFood' in (select * from #fields))
THEN [Animals].[AmountOfFood]
END AS [AmountOfFood]
The problem I'm facing is that (as could be expected) my SP went from taking ~200 ms to taking ~1 sec
Is there any way to maybe rewrite this so that it doesn’t kill us?
My kingdom for a foreach!!!
In SQL Server, you can also do this with dynamic SQL. Something like:
declare #sql nvarchar(max);
select #sql = (select ', '+
(case when FieldName = 'Food' then 'Foods.DisplayName'
when FieldName = 'AnimalAge' then 'Animals.Age'
. . .
end)
from #fields
for xml path ('')
);
select #sql = 'select [Animals].[AnimalID] AS [AnimalID], [Animals].[name] AS [AnimalName]'+#sql+RESTOFQUERY;
exec(#sql);
I'd try to convert the stored procedure into Table-Valued function, and make your grid select only required columns from it.
So your function would still select
SELECT
[Animals].[AnimalID] AS [AnimalID],
[Animals].[name] AS [AnimalName],
[Foods].[DisplayName] AS [Food],
[Animals].[Age] AS [AnimalAge],
[Animals].[AmountOfFood] AS [AmountOfFood]
If the client only selected for example select * AnimalID, Age from myfunction(..), only these columns would be transferred to the client.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 3 years ago.
This post was edited and submitted for review 5 months ago and failed to reopen the post:
Original close reason(s) were not resolved
Improve this question
Is there any particular reason (performance or otherwise) to use AS ahead of = when aliasing a column?
My current approach (for readability) is to use this:
select
alias1 = somecolumn
alias2 = anothercolumn
from
tables
etc...
instead of this:
select
somecolumn as alias1
anothercolumn as alias2
from
tables
etc...
Is there a performance or maintainability reason to use one over the other?
‘=’ isn't valid ANSI SQL, so you'll have difficulty should you wish to run your application on a different DBMS.
(It's when ANSI form is used but the optional ‘AS’ is omitted I find the results difficult to read, personally.)
To put in some counterweight, I prefer using =.
If I am the consumer of the query results in some way, I find it more convenient to see what columns I as a consumer can use.
I prefer this
SELECT
[ElementObligationID] = #MaxElementObligationID + eo.ElementObligationID
, [ElementID] = eo.ElementID
, [IsotopeID] = eo.IsotopeID
, [ObligationID] = eo.ObligationID
, [ElementWeight] = eo.ElementWeight * -1
, [FissileWeight] = eo.FissileWeight * -1
, [Items] = eo.Items * -1
, [Comment] = eo.Comment
, [AdditionalComment] = eo.AdditionalComment
, [Aanmaak_userid] = #UserID
, [Aanmaak_tijdstip] = GetDate()
, [Laatste_wijziging_userid] = #UserID
, [Laatste_wijziging_tijdstip] = GetDate()
FROM dbo.KTM_ElementObligation eo
INNER JOIN dbo.KTM_ElementObligationArticle eoa ON
eoa.ElementObligationID = eo.ElementObligationID
over this
SELECT
#MaxElementObligationID + eo.ElementObligationID AS [ElementObligationID]
, eo.ElementID AS [ElementID]
, eo.IsotopeID AS [IsotopeID]
, eo.ObligationID AS [ObligationID]
, eo.ElementWeight * -1 AS [ElementWeight]
, eo.FissileWeight * -1 AS [FissileWeight]
, eo.Items * -1 AS [Items]
, eo.Comment AS [Comment]
, eo.AdditionalComment AS [AdditionalComment]
, #UserID AS [Aanmaak_userid]
, GetDate() AS [Aanmaak_tijdstip]
, #UserID AS [Laatste_wijziging_userid]
, GetDate() AS [Laatste_wijziging_tijdstip]
FROM dbo.KTM_ElementObligation eo
INNER JOIN dbo.KTM_ElementObligationArticle eoa ON
eoa.ElementObligationID = eo.ElementObligationID
just my 2c.
I wouldn't use it simply as it looks far too much like equality operation. 'AS' is clear inasmuch that it's not ambiguous to me.
Its the same as not using upper case in sql, I find it harder to read.
I'm not as lucky as others who have posted here. The code I work with is usually written by someone else and it is rare that there are not CASE statements or other calculations, concatenations or logic that cause a single entry to span over several rows of T_SQL script.
Using a equal sign instead of 'AS' is by far easier to read. With an equal sign you know the alias name you are looking for is in the first position of the row. When 'AS' is used and the T_SQL spans multiple lines, the alias name could literally be anywhere.
It is far, far, far easier to find the 'Items' alias when equals is used than when 'AS' is used.
SELECT
ElementObligationID = #MaxElementObligationID + eo.ElementObligationID
, ElementID = eo.ElementID
, IsotopeID = eo.IsotopeID
, ObligationID = eo.ObligationID
, ElementWeight = eo.ElementWeight * -1
, FissileWeight = eo.FissileWeight * -1
, Items = CASE WHEN eo.Items < 0 THEN eo.Items * -1
WHEN eo.Items > 0 THEN eo.Items
ELSE 0 END
, Comment = eo.Comment
, AdditionalComment = eo.AdditionalComment
, Aanmaak_userid = #UserID
, Aanmaak_tijdstip = GetDate()
, Laatste_wijziging_userid = #UserID
, Laatste_wijziging_tijdstip = GetDate()
FROM dbo.KTM_ElementObligation eo
INNER JOIN dbo.KTM_ElementObligationArticle eoa ON
eoa.ElementObligationID = eo.ElementObligationID
Now imagine having more than 5 times the amount of code that is here and needing to find the 'Items' alias.
SELECT
#MaxElementObligationID + eo.ElementObligationID AS ElementObligationID
, eo.ElementID AS ElementID
, eo.IsotopeID AS IsotopeID
, eo.ObligationID AS ObligationID
, eo.ElementWeight * -1 AS ElementWeight
, eo.FissileWeight * -1 AS FissileWeight
, CASE WHEN eo.Items < 0 THEN eo.Items * -1
WHEN eo.Items > 0 THEN eo.Items
ELSE 0 END AS Items
, eo.Comment AS Comment
, eo.AdditionalComment AS AdditionalComment
, #UserID AS Aanmaak_userid
, GetDate() AS Aanmaak_tijdstip
, #UserID AS Laatste_wijziging_userid
, GetDate() AS Laatste_wijziging_tijdstip
FROM dbo.KTM_ElementObligation eo
INNER JOIN dbo.KTM_ElementObligationArticle eoa ON
eoa.ElementObligationID = eo.ElementObligationID
'AS' vs '=' is not a capricious and arbitrary preference. I am not exaggerating when I say there have been times when it would take several minutes to find the alias name I am looking for because the author of the script I am now in charge of maintaining did not use the equals sign with their alias. I cannot think of a bigger waste of time, money and resources than paying an IT professional to look for alias names in code!! There is a right and wrong answer if you care about maintainability, readability, and efficiency. Your job is to provide business value, not to spend your day looking for Waldo!
"=" is just plain ambiguous.
If you indent to break out each select clause...
select
alias1 = somecolumn,
alias2 = anothercolumn,
result = column1 * column2
from
table
....
select
somecolumn as alias1,
anothercolumn as alias2,
column1 * column2 as result
from
tables
...
= can be confused with assignment and equality; actually, the form I really don't like is when it looks like a string (usually when spaces are involved):
somecolumn as 'alias 1'
or
'alias 1' = somecolumn
I far prefer the alternative notation:
somecolumn as [alias 1]
The postfix alias form (with or without the "AS") is consistent between column and table aliases. Personally, I'd like an option to enforce the use of "AS", and then you wouldn't have the situation:
select
columnA,
columnB
columnC
from
table
producing a result set with two columns instead of the expected 3.
I'd also say that with the prefix "=" form, it can make it more difficult to read if you're mixing obtaining a result set and variable assignment:
select
cA = columnA,
#cB = columnB,
cC = columnC
from
table
The three ways I know of to alias:
TableColumn AS MyAlias
TableColumn MyAlias
MyAlias = TableColumn
Re: 1), I prefer this as it is the most self-documenting code (IMO), and it lets me search for AS if I need to find aliases..
Re: 2), This is my second choice, but without the AS, I am never sure whether this is a cut-and-paste error or not, especially in long, badly-formatted queries.
Re: 3), I don't like this because a) it looks like an assignment, and b) it blends in too much with ON clauses and CASE statements
So, my vote is to use the AS keyword for your aliases.
I prefer using AS since = is used in the where statement, and can be confusing in a long query.
I prefer using neither of those. I just give the name of the column without any keyword in between
SELECT MAX(price_column) maximumprice FROM prices
Column aliases declared by "=" syntax are deprecated in SQL Server 2008 and not supported in the next version. See MSDN article.
While I have a preference for using AS, the really key thing here is to have a corporate standard and to follow it. If more of your people use AS than = then everyone should use it. Coding standards are what makes it easier to maintain code not the particular standard you pick. If everyone uses the same thing, then your eye gets used to picking it out.
I like the
SELECT
column1 = table.column1
,column2 = table.colum2
FROM table
I find AS not as easily noticable compared to a = sign (I can spot = quicker than AS)
Also when one just does SELECT column alias, sometimes it's confusing to know which one is which :)
Since I write SQL for several different relational database management systems, I prefer to use a syntax which works on all of them, which normally means writing ANSI compatible SQL. My normal formatting preference is:
SELECT
S.name AS SchemaName,
O.name AS ObjectName,
C.column_id AS ColumnId,
C.name AS ColumnName
FROM
sys.schemas AS S
INNER JOIN sys.objects AS O ON S.schema_id = O.schema_id
INNER JOIN sys.columns AS C ON O.object_id = C.object_id
ORDER BY
S.name ASC,
O.name ASC,
C.column_id ASC;
As an alternative formatting of the above, the following makes it easier to see the column alias names:
SELECT
S.name
AS SchemaName,
O.name
AS ObjectName,
C.column_id
AS ColumnId,
C.name
AS ColumnName
FROM
sys.schemas AS S
INNER JOIN sys.objects AS O ON S.schema_id = O.schema_id
INNER JOIN sys.columns AS C ON O.object_id = C.object_id
ORDER BY
S.name ASC,
O.name ASC,
C.column_id ASC;
**even i prefer using 'as' instead of '=' . '=' makes confusion in code.
e.g :
column as alias1
You don't have to use either
Drop the AS and use
SELECT originalname alias
FROM
tablename