Use a named custom column in SQL 2005 in WHERE clause? - sql

Can I name a custom column in the SELECT statement and reference that in the WHERE clause without duplicating code?
For example;
SELECT RIGHT(REPLICATE('0', 5) + RTRIM(SOME_ID)), 5) AS DISPLAY_ID
FROM dbo.MY_TABLE
WHERE DISPLAY_ID LIKE '%005%'
Only much more complicated. I want to maintain this code in one place only but SQL Server 2005 forces me to duplicate the custom SELECT in the WHERE clause.
I believe this was possible in Microsoft SQL Server 2000 but no longer in 2005.
Thanks.

You can do this using either a SUB SELECT or a CTE function
SELECT *
FROm (
SELECT RIGHT(REPLICATE('0', 5) + RTRIM(SOME_ID), 5) AS DISPLAY_ID
FROM MY_TABLE
) sub
WHERE DISPLAY_ID LIKE '%005%'
OR
;WITH Tbl AS(
SELECT RIGHT(REPLICATE('0', 5) + RTRIM(SOME_ID), 5) AS DISPLAY_ID
FROM MY_TABLE
)
SELECT *
FROM Tbl
WHERE DISPLAY_ID LIKE '%005%'
One of the times that I am aware of that you can use the column alias, is when you wish to ORDER BY that column alias.
EDIT:
Multiple CTE blocks
DECLARE #MY_TABLE TABLE(
SOME_ID INT
)
DECLARE #Your_TABLE TABLE(
SOME_ID INT
)
;WITH Table1 AS(
SELECT *
FROM #MY_TABLE
),
Table2 AS(
SELECT *
FROM #Your_TABLE
)
SELECT *
FROM Table1 t1 INNER JOIN
Table2 t2 ON t1.SOME_ID = t2.SOME_ID

You can wrap it using a subselect a bit cleaner, like this:
SELECT DISPLAY_ID
FROM (SELECT RIGHT(REPLICATE('0', 5) + RTRIM(SOME_ID)), 5) AS DISPLAY_ID
FROM dbo.MY_TABLE) SubTable
WHERE DISPLAY_ID LIKE '%005%'

Related

Save a Select/Except Union into a Temp Table

This code does precisely what I want: finds the difference between two tables, including nulls, and returns them. Thanks to: sql query to return differences between two tables
(
SELECT * FROM table1
EXCEPT
SELECT * FROM table2
)
UNION ALL
(
SELECT * FROM table2
EXCEPT
SELECT * FROM table1
)
I am having trouble getting this to turn into a temporary table (or even a regular table) to store its results for later use. Is there a way that I can tack on INSERT INTO here or generate a temp table from this beautiful query?
Select from your existing query as a sub-query INTO the temp table of your choice.
SELECT *
INTO #temp1
FROM (
(
SELECT * FROM #table1
EXCEPT
SELECT * FROM #table2
)
UNION ALL
(
SELECT * FROM #table2
EXCEPT
SELECT * FROM #table1
)
) X

How can i use the replace statement in query

I am trying to query a table that has values separated by commas as follows:
SELECT ID, NAME,FULLNAME,STATUS,STORE
FROM EMPLOYEE
WHERE STORE IN (SELECT '''' + REPLACE('001,002',',',''',''') +'''')
ORDER BY STORE
when I run the query above, it produces no results,
but when I run it like this:
SELECT ID, NAME,FULLNAME,STATUS,STORE
FROM EMPLOYEE
WHERE STORE IN ('001','002')
ORDER BY STORE
I get like 500 records.
And when I try this:
SELECT ('''' + REPLACE('001,002',',',''',''') +'''')
I get the result '001','002'
so my question is, why the first script does not work, and produces no results?
Is there something I must add to the script for it to work?
please advise.
What if I had this scenario
SELECT ID, NAME,FULLNAME,STATUS,STORE
FROM dbo.EMPLOYEE
WHERE STORE IN (
SELECT t2.ID
FROM (
SELECT Value = REPLACE('001,002', ',', '.')
) t
CROSS APPLY (
VALUES
(PARSENAME(t.Value, 1)),
(PARSENAME(t.Value, 2))
) t2 (ID)
)
AND STATUS IN (
SELECT t2.ID1
FROM (
SELECT Value1 = REPLACE('A,T,L', ',', '.')
) t1
CROSS APPLY (
VALUES
(PARSENAME(t1.Value1, 1)),
(PARSENAME(t1.Value1, 2))
) t2 (ID1)
)
ORDER BY STORE
I tried that, and it didn't work, so I am just wondering if it works for more than 1 condition.

Set criteria to be used in multiple SQL select queries

Need to set criteria for running multiple queries, but only want to change once. For example, want to set year, period, document so that...
select * from tbl1 where tbl1.yr = year and ...
select * from tbl2 where tbl2.yr = year, and ...
Create a view:
CREATE VIEW yourview AS
SELECT * from tbl1
UNION ALL
SELECT * from tbl2
Then query it:
SELECT * FROM yourview
WHERE tbl1.yr = year AND ...
You may also want to know from which table each row comes. This can be achieved by adding an extra column to the view:
CREATE VIEW yourview AS
SELECT 'tbl1' AS src, * from tbl1
UNION ALL
SELECT 'tbl2' AS src, * from tbl2
If they're truly different queries, not related, you may have to resort to Dynamic SQL, e.g.
DECLARE #sCondition VARCHAR(50)
SET #sCondition = 'yr = 2012'
DECLARE #sQuery1 VARCHAR(1000)
SET #sQuery1 = 'select * from tbl1 where ' + #sCondition
-- DECLARE other queries in similar faction OR combine multiple queries into single variable
EXEC (#sQuery1)
With CTE; Note: you should have same number of columns and matching datatypes from both tables as you are doing a blind union of select *
;with cte (myYear)
as (
select #year as myYear
)
select * from table1 t1 where t1.year in (select myYear from cte)
union all
select * from table2 t2 where t2.year in (select myYear from cte)

Why doesn't SQL DISTINCT work with ORDER BY CAST?

Including DISTINCT to an SQL query that also uses ORDER BY CAST(thecolumn AS int) as shown here seems to remove that sorting functionality.
Any reason these cant work together?
(Using sqlite with the C api)
Thanks.
EDIT:
Started with -
sprintf(sql, "SELECT DISTINCT rowX FROM TableX Order By Cast(rowX As int) LIMIT 150 OFFSET %s;", Offset);
rowX is Type CHAR(5)
NOW:
sprintf(sql, "Select rowX FROM(Select Distinct rowX From TableX)t Order By Cast(rowX As int) LIMIT 150 OFFSET %s;", Offset);
I used the following with sqlite, and sorting worked fine:
Select Distinct thecolumn
From your_table
Order By Cast(thecolumn As int)
Have you tried putting the DISTINCT into a sub-query?
Select thecolumn
From
(
Select Distinct thecolumn
From your_table
) t
Order By Cast(thecolumn As int)
I would expect it to work that way.
One more way:
Select thecolumn
From
(
Select Distinct Cast(thecolumn As int) As thecolumn
From your_table
) t
Order By thecolumn
This is way super late, but the order by has to match the select list exactly so:
select distinct cast(column as int)
from table
order by cast(column as int)

the row no in query output

I have a numeric field (say num) in table along with pkey.
select * from mytable order by num
now how I can get the row no in query output of a particular row for which I have pkey.
I'm using sql 2000.
Sounds like you want a row number for each record returned.
In SQL 2000, you can either do this:
SELECT (SELECT COUNT(*) FROM MyTable t2 WHERE t2.num <= t.num) AS RowNo, *
FROM MyTable t
ORDER BY num
which assumes num is unique. If it's not, then you'd have to use the PK field and order by that.
Or, use a temp table (or table var):
CREATE TABLE #Results
(
RowNo INTEGER IDENTITY(1,1),
MyField VARCHAR(10)
)
INSERT #Results
SELECT MyField
FROM MyTable
ORDER BY uum
SELECT * FROM #Results
DROP TABLE #Results
In SQL 2005, there is a ROW_NUMBER() function you could use which makes life a lot easier.
as i understand your question you want to get the number of all rows returned, right?
if so use ##rowcount
As Ada points out, this task became a lot easier in SQL Server 2005....
SELECT whatever, RowNumber from (
SELECT pk
, whatever
, ROW_NUMBER() OVER(ORDER BY num) AS 'RowNumber'
FROM mytable
)
WHERE pk = 23;