How to select wanted column from select query based on condition - sql

I have select query which returns
id ,name ,description ,price
Im trying to get id,price alone based on condition it should display name ,description
#show =1
select id ,name,if #show = 1 begin name ,description, end ,price from tbl
Thanks

#show =1
if #show = 1
begin
select id, name, description, price from tbl
end
else begin
select id, price from tbl
end

You can join the columns you want and execute the query.
DECLARE #filter AS Integer
DECLARE #columns AS nvarchar(50)
DECLARE #sql AS nvarchar(50)
Set #filter = 1
if #filter = 0
begin
Set #columns = 'id, name, description, price'
end
else begin
Set #columns = 'id, name'
end
set #sql = 'select ' + #columns + ' from tbl'
EXECUTE sp_executesql #sql
print #sql

Based on your comment
i pass show parameter as 0 or 1,if 0 only have to select id , price if i pass 1 it select all 4 column
CREATE PROCEDURE MyProc
#Show BIT = 1 --i pass show parameter as 0 or 1 That means BIT Datatype(True/False)
AS
IF #Show = 0
SELECT ID, Price --if 0 only have to select id , price
FROM Table
ELSE
SELECT * --if i pass 1 it select all 4 column
FROM Table

Your all answer helped me a lot,thanks.
finally i went this method works on string concat
fields are id,name,description,price
declare #id int;
declare #sqlcommand nvarchar(max) ;
declare #visible int ;
set #sqlcommand = 'select id ,'+case when #visible = 1 then 'name ,description' else '' end +',price from tbl
where id = #id'
execute sp_executesql #sqlCommand ,N'#id int',#id=#id
if i pass visible = 1
result will be
id name desc price
visible = 0
id price
Thanks

Related

How can I merge this query result set into a variable to print out later?

so I have this currently
SET #title = (SELECT title FROM fnBorrowerBooks(#name, 'G3'))
SET #dateBorrowed = (SELECT DateBorrowed FROM fnBorrowerBooks(#name, 'G3'))
SET #dateReturned = (SELECT DateReturned FROM fnBorrowerBooks(#name, 'G3'))
but basically what I would need is something like
SET #variable 1 = (SELECT * FROM fnBorrowerBooks(#name, #Genre)
But this returns 3 columns and CAN return multiple ROWS which obviously won't work because you can't assign multiple values, I need to print how many results I get so if I get 3 different results I need to print all 3 as in 1 string if that makes sense so
PRINT CONCAT(#variable1, ' ble ble ble') should return me multiple lines depending on how many results there are, and I was unable to find a way on how to achieve this.
If you only need the titles then you can concatenate within your query:
DECLARE #Title NVARCHAR(3000)
SELECT
#Title = COALESCE(#Title + ', ', '') + title
FROM
dbo.fnBorrowerBooks(#name, #genre)
SELECT #title
You could try using a temp table and a loop, like this:
CREATE TABLE #t
(tKey int IDENTITY(1,1) PRIMARY KEY,
Column1 varchar(100),
Column2 varchar(100),
...)
INSERT INTO #t
SELECT * --the columns you select here need to be in the column list above
FROM fnBorrowerBooks(#name, #Genre)
DECLARE #Count int
DECLARE #MyString varchar(max)
SET #Count = 1
SET #MyString = ''
WHILE #Count <= (SELECT MAX(Key) FROM #t)
BEGIN
SET #MyString += (SELECT Column1 + ', ' + Column2 + ... FROM #t WHERE tKey = #Count)
SET #Count += 1
END
PRINT(#MyString)

Comma Separated List from SQL Grouping

I'm trying to build comma separated list per group in sql,
As am using Parallel Data Warehouse i need to do this without using FOR XML or recursive function ( not supported ).
any other way to achieve this ?
Input:
ID Value
1 2
1 3
1 4
2 1
2 10
Output:
ID List
1 2,3,4
2 1,10
This will not perform well at all so I recommend you use some other solution (like a SQL Server linked server to PDW) if you need performance. But I believe this should work on PDW:
declare #ID int = (select min(ID) from tbl);
declare #Value int = -1;
declare #concat varchar(8000) = '';
create table #tmp (
ID int,
[concat] varchar(8000)
)
with (distribution=hash(ID), location=user_db);
while #ID is not null
begin
set #Value = (select min([Value]) from tbl where ID = #ID and [Value]>#Value);
if #Value is not null
set #concat = #concat + case when #concat = '' then '' else ',' end + cast(#Value as varchar(8000));
else
begin
insert #tmp (ID, [concat])
values (#ID, #concat);
set #ID = (select min(ID) from tbl where ID > #ID);
set #Value = -1;
set #concat = '';
end
end
select * from #tmp;
drop table #tmp;

if user-defined type is null then select whole table

I have a user-defined type as below
CREATE TYPE [dbo].[HaveItemUdt] AS TABLE(
[Defindex] [int] NULL
)
In my stored proc
#HaveItemList AS HaveItemUdt READONLY
SELECT * FROM tbl_something WHERE itemID IN (SELECT itemID FROM #HaveItemList)
When the #HaveItemList is empty, i want to select the whole table like this
SELECT * FROM tbl_something WHERE itemID IN (SELECT itemID FROM tbl_something )
I try this but doesn't work
SELECT * FROM tbl_something WHERE itemID IN (SELECT itemID FROM #HaveItemList) OR #HaveItemList IS NULL
Any idea how to do this?
you can use not exists.
select *
from tbl_something
where ( not exists(select 1 from #HaveItemList )
or itemID in (select Defindex from #HaveItemList ))
the idea is that the first part will return true if #HaveItemList is empty and so the following IN clause is 'ignored'
You could do this using dynamic SQL.
DECLARE #HaveItemList int
SET #HaveItemList = 5
DECLARE #sql nvarchar(max)
SET #sql = 'SELECT * FROM tbl_something WHERE itemID IN (SELECT itemID FROM '
SELECT #sql = #sql +
CASE
WHEN #HaveItemList IS NULL THEN ' TblSomething)'
ELSE '' + CAST(#HaveItemList AS varchar) + ')'
END
PRINT #sql
-- EXEC sp_executesql #sql -- Uncomment to execute the generated statement
If you comment the second line where the value for #HaveItemList is set, it'll evaluate to NULL, and the select will be done on the table.

How to retrieve N random records from stored procedure?

How can I retrieve N random records from a set of X records we have in total. For example, if we have a table with 2000 links to different pages on our website how do we retrieve 10 random records?
SELECT TOP 10 *
FROM tableName
ORDER BY NEWID()
NEWID
Try using dynamics SQL like this. Note that this needs more work since some edge cases are not covered such as COUNT() returning 0 or cases where record count is greater than COUNT() and such.
CREATE PROCEDURE dbo.RandomNRecords
(
#recordCount int
)
as
begin
declare #counter int
declare #sqlQuery nvarchar(2000)
SET #sqlQuery = '
CREATE TABLE #TempTable
(
f1 varchar(50),
f2 varchar(50),
f3 int,
id int identity(1,1)
)
INSERT INTO #TempTable
SELECT f1, f2, f3 FROM Table1
SELECT *
FROM #TempTable
WHERE id in ('
SELECT #recordCount = COUNT(*) From Table1
SET #counter = 0
WHILE #counter < #recordCount
BEGIN
SET #counter = #counter + 1
SET #sqlQuery = #sqlQuery + CONVERT(varchar,Round((#recordCount * Rand()), 0)) + ','
END;
SET #sqlQuery = SUBSTRING(#sqlQuery, 1, LEN(sqlQuery) - 1) --remove last comma
SET #sqlQuery = #sqlQuery + ')'
EXEC sp_executesql #sqlQuery
END
declare #numberOfRecordsToGet int = 5
select top (#numberOfRecordsToGet) * from name_of_your_tbl order by newid()
use this in store procedure
declare #N varchar(10)
set #N='10'
exec(' SELECT TOP '+#N+' * FROM tableName ORDER BY NEWID()')

Convert sql results to 'select UNION select' query (exportable data)

Sometimes we need to debug with our client data and we dont have time to take a complete database backup so we convert manually a sql result to a combination of static 'select UNION select UNION' so we can use their data on the fly...
Example:
select * from items
Results:
Itemcode ItemName Price
Car1 FerrariX 1200.00
Car2 FerrariZ 3000.00
Car3 MustangR 2100.00
And we bring it back to our debuging enviroment like this:
select 'Car1' as Itemcode, 'FerrariX' as Itemname, 1200.00 as 'Price' UNION
select 'Car2', 'FerrariZ', 3000.00 UNION
select 'Car3', 'MustangR', 2100.00
Posible Stored Procedure Solution:
EXEC spQueryAsStaticData #Query = 'select * from items'
How can we do this transformation automatically? Some stored procedure?
i use something like this to print out text using data
DECLARE #i int
DECLARE #employee_id int
Declare #Hash nvarchar(max)
declare #Result nvarchar(max)
Declare #String nvarchar(MAX)
DECLARE #numrows int
DECLARE #employee_table TABLE (
idx smallint Primary Key IDENTITY(1,1)
, [ID] int , [Hash] nvarchar(50), Result nvarchar(50)
)
INSERT #employee_table
SELECT Top 5 * FROM [Hlist].[dbo].[MD5]
set #i =0
set #String = ''
SET #numrows = (SELECT COUNT(*) FROM #employee_table)
IF #numrows > 0
WHILE (#i <= (SELECT MAX(idx) FROM #employee_table))
BEGIN
-- get the next employee primary key
SET #employee_id = (SELECT ID FROM #employee_table WHERE idx = #i)
SET #Hash = (SELECT Hash FROM #employee_table WHERE idx = #i)
SET #Result = (SELECT Result FROM #employee_table WHERE idx = #i)
Set #String = coalesce(#String +'Select '+ convert(varchar,#employee_id) + ', ' +#Hash+ ', '+#Result +' Union ', '')
--
-- do something with this employee
--
-- increment counter for next employee
SET #i = #i + 1
END
Print #String
In the end we solved it developing a little C# app, not as useful as generating it directly from a SQL query but it works...
If someone gives the SQL solution we will grant the answer to him/her