dynamic column name in where clause - sql-server

declare #temp varchar(20)
declare #name varchar(20)
set #name = 'John'
set #temp = 'e'
select * from TableA
where case when #temp = 'e' then [em_name]
case when #temp = 'c' then [company_name]
end
= #name
This query is giving me error(A non-Boolean expression in where clause).
Please explain what is wrong in this query and how can i achieve this without dynamic sql.
so when i give #temp = 'C' then it should search for [company_name] = #name. and have a long list of #temp values(employee name, company name, city name, state name, supervisor name etc).

There is a syntax error in the snip you posted:
where case when #temp = 'e' then [em_name]
case when #temp = 'c' then [company_name]
end
= #name
Should be:
WHERE CASE WHEN #temp = 'e' THEN em_name
WHEN #temp = 'c' THEN company_name
END = #name
Note there is now only one CASE keyword. Here's the more common syntax (for completeness):
DECLARE #temp VARCHAR(20)
DECLARE #name VARCHAR(20)
SET #name = 'John'
SET #temp = 'e'
SELECT *
FROM TableA
WHERE (#temp = 'e' AND [em_name] = #name)
OR (#temp = 'c' AND [company_name] = #name)

SELECT *
FROM TableA
WHERE (#temp = 'e' AND [em_name] = #name) OR (#temp = 'c' AND [company_name] = #name)

Related

Compare Identical Columns of 2 Different Table for Mismatch Data

I have the following query to check if usernames are the exact same between to tables
SELECT
--Username
a.username as 'TABLE_1_USERNAME',
b.username as 'TABLE_2_USERNAME',
CASE
WHEN a.username IS NULL AND b.username IS NULL THEN 'True'
WHEN a.username = b.username THEN 'True'
ELSE 'False'
END AS 'Is Equal?'
FROM User a
JOIN User_Group b ON a.id = b.id
This works great to tell me if usernames differ for any reason, but what I'd like to do is recursively compare each column between the User table and the User_Group Table (without having to write each one out) - both of the table's column names are identical. Is this possible in SQL Server?
Leaving out casing checks and trimming for brevity
Try this. Except shows any rows in the two queries that don't fully match
SELECT * FROM User_Group
EXCEPT
SELECT * FROM User
Here's a dynamic sql method for doing literally what you're asking for:
DECLARE #cols TABLE (id int identity(1,1), colname varchar(25))
INSERT INTO #cols (colname) select COLUMN_NAME from INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'User' AND COLUMN_NAME <> 'id'
declare #sql nvarchar(max)
select #sql = 'SELECT a.id, '
declare #maxval int
select #maxval = max(id) from #cols
declare #c int = 1
declare #curcol varchar(25)
while #c <= #maxval
begin
if #c > 1
select #sql += ', '
select #curcol = colname from #cols where id = #c
select #sql += 'a.' + #curcol + ' as ''Table_1_' + #curcol + ''', b.' + #curcol + ' as ''Table_2_' + #curcol + ''',
CASE
WHEN a.' + #curcol + ' IS NULL AND b.' + #curcol + ' IS NULL THEN ''True''
WHEN a.' + #curcol + ' = b.' + #curcol + ' THEN ''True''
ELSE ''False''
END AS ''Is Equal?'''
set #c = #c + 1
end
select #sql += 'FROM [User] a
INNER JOIN User_Group b ON a.id = b.id'
exec sp_executesql #sql
With the following test data:
create table [User] (id int, username varchar(10), fname varchar(25), lname varchar(25))
create table [User_Group] (id int, username varchar(10), fname varchar(25), lname varchar(25))
insert into [User] values (1, 'user1', 'fname1', 'lname1')
insert into [User_Group] values (1, 'user1', 'fname1', 'lname1')
insert into [User] values (2, 'user2', 'fname2', 'lname2')
insert into [User_Group] values (2, 'user2', 'fnameasdf', 'lnamesdfg')
It generates this output:
id Table_1_username Table_2_username Is Equal? Table_1_fname Table_2_fname Is Equal? Table_1_lname Table_2_lname Is Equal?
1 user1 user1 True fname1 fname1 True lname1 lname1 True
2 user2 user2 True fname2 fnameasdf False lname2 lnamesdfg False
Here's the query it generates:
SELECT a.id, a.username as 'Table_1_username', b.username as 'Table_2_username',
CASE
WHEN a.username IS NULL AND b.username IS NULL THEN 'True'
WHEN a.username = b.username THEN 'True'
ELSE 'False'
END AS 'Is Equal?', a.fname as 'Table_1_fname', b.fname as 'Table_2_fname',
CASE
WHEN a.fname IS NULL AND b.fname IS NULL THEN 'True'
WHEN a.fname = b.fname THEN 'True'
ELSE 'False'
END AS 'Is Equal?', a.lname as 'Table_1_lname', b.lname as 'Table_2_lname',
CASE
WHEN a.lname IS NULL AND b.lname IS NULL THEN 'True'
WHEN a.lname = b.lname THEN 'True'
ELSE 'False'
END AS 'Is Equal?'FROM [User] a
INNER JOIN User_Group b ON a.id = b.id

combine two T-SQL in a dynamic way

How can I using something like if or case..when to combine the following code into one?
if #para = 'test'
begin
select * from Table A where status='A' and id in (select id from Table B)
end
else if #para = 'others'
begin
select * from Table A where status='A' and id in (select id from Table c)
end
like select * from Table A where id in if #para = XXX then (select id from Table B)
Thanks a lot.
Try this:
select *
from Table A
where (id in (select id from Table B) and #para = 'test')
OR
(id in (select id from Table c) and #para = 'others')
As you tagged stored procedure i made it as one ... try it like this
create procedure GetData (#para nvarchar(100))
as
begin
declare #sql nvarchar(max)
set #sql = case
when #para = 'test'
then
'Select * from TableA A
join TableB B on A.id = B.ID'
else -- if #para = 'others' goes into else
'Select * from TableA A
join TableB B on A.id = B.ID'
end
execute (#sql)
end

Get Float value with Comma separtor

Am new to Sql server ce. my table have float value. I want select float with comma separated and decimal position. like this
table name table1
val
1220333
222
36535
I want result like this
val
12,20,333.00
222.00
36,535.00
like indian Rupees
Am using Sql server ce 3.5
DECLARE #Table1 TABLE
(val int)
;
INSERT INTO #Table1
(val)
VALUES
(1220333),
(222),
(36535)
;
select convert(varchar(50), CAST(val as money), -1) amount from #Table1
select FORMAT(CAST(val AS MONEY),'N','en-in') amount from #Table1
OR
Function
create function to_indian_currency(#n decimal(25,5))
returns varchar(100) as
BEGIN
declare #a varchar(100) = cast(#n as varchar(100))
declare #dec_part varchar(100) =
(select substring(#a, charindex('.',#a), len(#a)-charindex('.',#a)+1))
declare #int_part varchar(100) = (select left(#a, charindex('.',#a)-1))
declare #f int = cast(#int_part as bigint)%1000
declare #q int = cast(#int_part as bigint)/1000
declare #final varchar(100) = ''
while #q > 0
begin
set #final = cast(#q%100 as varchar) + ',' + #final
set #q = #q/100
end
RETURN #final + cast(#f as varchar) + #dec_part
END
select dbo.to_indian_currency(val) from #Table1

MS SQL Stored procedure returning unexpected results based on blank parameters

I'm passing parameters to a stored procedure from an asp.net webform.
However, for one particular combination of parameters a single parameter appear to being ignored.
The parameters I'm passing that are causing the issue are as follows:
EXEC #return_value = [dbo].[spProgressCohorts]
#StuYear = N'10',
#DataCollection = N'March 2013 Teacher Assessments',
#SubjectName = N'English',
#TeachingGroup = N'Select All',
#Subgroup = N'Select All',
#KS2 = '',
#Result = ''
When I run the stored procedure with these parameters the results return as though the #Result variable is being ignored.
The results the stored procedure return are (the ks2en and result columns are included for reference):
surname forename ks2en result
El Hajj Zeinab D
Grzelak Marlena F+
Sage Nigel
However, I get just get Nigel Sage's record (as expected and this is what should be returned by the stored procedure) when when I run the following query:
select surname, forename, ks2en, result
from student join subject on subject.upn=student.upn
where datacollection='March 2013 Teacher Assessments' and stuyear='10' and name='english' and result='' and ks2en=''
My stored procedure is massive, so I'll just include code specific to the parameters above:
ALTER PROCEDURE [dbo].[spProgressCohorts]
#StuYear varchar(2),
#DataCollection varchar(100),
#SubjectName varchar(100),
#TeachingGroup varchar(30),
#Subgroup varchar(10),
#Result varchar(4),
#KS2 varchar(4)
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
--interfering with SELECT statements.
SET NOCOUNT ON;
SELECT Forename + ' ' + Surname
FROM student
JOIN subject
ON subject.upn = student.upn
WHERE
(#StuYear = [stuyear]
AND #TeachingGroup = 'Select All'
AND [DataCollection] = #DataCollection
AND [Name] = #SubjectName
AND #Subgroup='Select All'
AND #KS2 = CASE #subjectName WHEN 'English' THEN KS2en WHEN 'Mathematics' THEN KS2ma ELSE KS2av END
AND [Result] like #Result + '%')
OR
(#StuYear = [stuyear]
AND #TeachingGroup Not Like 'Select All'
AND [DataCollection] = #DataCollection
AND [Name] = #SubjectName
AND [TeachingGroup] = #TeachingGroup
AND #Subgroup='Select All'
AND #KS2 = CASE #subjectName WHEN 'English' THEN KS2en WHEN 'Mathematics' THEN KS2ma ELSE KS2av END
AND [Result] like #Result + '%')
ORDER BY surname, forename
How about this?
...
AND [Result] LIKE CASE #Result WHEN '' THEN '' ELSE #Result + '%' END)

Inserting using CSV

I have a table with two fields Name and ID.
Name comes from input parameter #Name and ID comes a CSV #CSVID.
I have a spilt function that return a temp table .
My stored proc is
INSERT INTO dbo.MyTable
(
Name,
ID
)
VALUES
(
(SELECT #Name, id FROM dbo.Split(#CSVID))
)
My split function
ALTER FUNCTION [dbo].[Split] (#InStr VARCHAR(MAX))
RETURNS #TempTab TABLE
(id int not null)
AS
BEGIN
;-- Ensure input ends with comma
SET #InStr = REPLACE(#InStr + ',', ',,', ',')
DECLARE #SP INT
DECLARE #VALUE VARCHAR(1000)
WHILE PATINDEX('%,%', #INSTR ) <> 0
BEGIN
SELECT #SP = PATINDEX('%,%',#INSTR)
SELECT #VALUE = LEFT(#INSTR , #SP - 1)
SELECT #INSTR = STUFF(#INSTR, 1, #SP, '')
INSERT INTO #TempTab(id) VALUES (#VALUE)
END
RETURN
END
So what I want is
say
#Name = 'John Doe'
#CSVID = '1,2'
Then I want the result of insert to be
Name ID
John 1
Jhon 2
I saw so many example but they were all so complicated. I just a simple explanation as to how insert works if the subquery
SELECT * FROM dbo.Split(#CSVID)
returns more than 1 value.
Thanks
INSERT INTO dbo.MyTable(Name, ID)
SELECT #Name,
id
FROM dbo.Split(#CSVID)

Resources