create a dummy column and populate with select - sql-server

I need to use a select query to create a dummy column and pad it with a constant value. I found a partial answer to my question in a related post, here was the answer:
select name, address, 'No' as vacationing, Zipcode from mytable;
My question is what do you do if you want to pad it with a number, such as:
'9999' AS vacationing - I get an error with that
Also, what if I want the cell to be empty, such as;
'' AS vacationing - I get an error here also
TIA

'9999' AS vacationing is perfectly valid.
you must be using union with different column type - hence error.

SELECT name, address, '9999' AS vacationing, Zipcode FROM mytable;
And:
SELECT name, address, '' AS vacationing, Zipcode FROM mytable;
Are both valid T-SQL queries. You don't say what error you're getting, but neither of these should throw an error.

Related

View failing on data conversion - SQL Server

I need help redesigning a view. Currently it is giving an error when you do a simple select of the view. The error is as follows.
Error converting data type nvarchar to bigint
This is the current design of the view.
SELECT
FirstName,
MiddleName,
LastName,
CONVERT(bigint, SUBSTRING(Reference, 2, 10)) AS LogNum,
Address,
Birthday,
Gender,
BirthDate,
Gender,
ClientCode
FROM
dbo.Client
WHERE
(Reference LIKE 'C%')
The issue is happening because the reference column which has a nvcarchar(16) datatype has values that are as follows.
'C3456423445'
'2234567310'
'C8921244532'
The substring function basically strips out the "C" and returns the 10 digit numbers after it as a bigint.
What is happening now is there is new data that came into the client table that has values for reference column as follows
"CC4309842387"
"CC29383761760"
Since there is an extra C in the new values, the function is not doing its job.
I need to redesign the view so that it can handle both iterations of the values in the reference column. What is essential is the 10 digit numbers coming out intact for the front end report.
Thank you for your help.
If there are only two options "C" and "CC", then you can use REPLACE with LEFT instead of SUBSTRING.
SELECT
FirstName,
MiddleName,
LastName,
Convert(bigint,Left(Replace(Reference, 'C',''),10)) AS LogNum,
Address,
Birthday,
Gender,
BirthDate,
Gender,
ClientCode
FROM dbo.Client
WHERE (Reference LIKE 'C%')
If other than preceding C's, you can use patindex() to find the position of the 1st numeric
Also, I prefer try_convert() because if the conversion fails, it will return a NULL rather than throwing an error.
Example
Declare #YourTable Table ([Reference] nvarchar(50)) Insert Into #YourTable Values
('C3456423445')
,('2234567310')
,('C8921244532')
,('CC29383761760')
,('XX29383761760')
Select *
,NewValue = try_convert(bigint,substring([Reference],patindex('%[0-9]%',[Reference]),25))
from #YourTable
Results
Reference NewValue
C3456423445 3456423445
2234567310 2234567310
C8921244532 8921244532
CC29383761760 29383761760
XX29383761760 29383761760

Convert SSRS parameter to Null

I have SSRS report that showing Marketing Features. we have in the MF a field called "Test", the values are "PSI 1" or PSI 2" and also the field can be empty.
I added a dataset for the Test parameter with this query:
SELECT DISTINCT Corp_Test
FROM [Tfs_Warehouse].[dbo].[CurrentWorkItemView]
WHERE ProjectNodeGUID = #ProjectGuid
AND System_WorkItemType = 'Marketing Feature'
UNION
SELECT 'Null'
ORDER BY Corp_Test
Now in the report, the values are PSI 1 PSI 2 and Null:
In the Main Query I filtered the results according to the parameter like this:
where COALESCE(Corp_Test, 'Null') IN (#TestParam)
The report works fine, and if I selected all values I get also Marketing Features with empty Test field.
My question is:
Instead of Null on the dropdown, I want it to be written No PSI and actually in the main query it will be Null. is it possible?
In your parameter properties, on the Available Values screen you will see an option for the Value and the Label. This allows you to show one thing to the end user (eg: user friendly description) whilst passing another (eg: key value) to the report.
In your dataset for the test parameter add a column to hold the Label of the value you want to pass through to the query. This can be the same as your Value if you so wish, but gives you the flexibility you require on the Null entry:
SELECT DISTINCT Corp_Test as Value
,Corp_Test as Label
FROM [Tfs_Warehouse].[dbo].[CurrentWorkItemView]
WHERE ProjectNodeGUID = #ProjectGuid
AND System_WorkItemType = 'Marketing Feature'
UNION ALL -- As you have DISTINCT above, UNION ALL will work faster and give the same results as UNION (which removes duplicates)
SELECT 'Null' as Value
,'No PSI' as Label
ORDER BY Corp_Test
Once you have done this, change your parameter to use the Value field as the parameter value and the Label field as the label shown to the user.
SELECT
ISNULL(Corp_Test,'No PSI') AS Corp_Test
FROM
(SELECT DISTINCT Corp_Test
FROM [Tfs_Warehouse].[dbo].[CurrentWorkItemView]
WHERE ProjectNodeGUID = #ProjectGuid
AND System_WorkItemType = 'Marketing Feature'
UNION
SELECT 'Null'
) AS Corp
ORDER BY ISNULL(Corp_Test,'No PSI')
Remember to implement the change in your where clause main query. By main query, I mean the query that is feeding your report
The simple and easiest way is what #sgeddes answered in his comment.
I just repleced the where COALESCE(Corp_Test, 'Null') IN (#TestParam) with where COALESCE(Corp_Test, 'No PSI') IN (#TestParam), and in the dataset I replaced the SELECT 'Null' with SELECT 'No PSI'.

Order by in union clause

Could any one please help me I have been working on a query containing unions n joins of multiple tables.. I have got the desired results but I want to get these results in some specific order so the whole result is being orderd according to one column.
Here is the snippet of code I am working on:
select name, age
from UserUni
order by age
union all
select age, Name
from UserOffice
order by age
Just add an ORDER BY clause at the very end of the UNION query, and it should be applied to the entire query:
select name, age
from UserUni
union all
select name, age
from UserOffice
order by age
Note that I swapped the order of the columns appearing in the second half of the UNION query because it doesn't make sense to put age and name into the same column. It is generally a requirement in a UNION query that the types and number of all columns be the same in boths halves of the query. One exception might be MySQL, which might appear to allow mixing numbers and text, but even in this case some implicit type conversion would be happening underneath the hood.
when we are using we can not use order by with both statements. because union at the end give one result end so how is it possible to use two order by statements.
you can check details here.
https://finalcodingtutorials.blogspot.ae/2017/03/order-by-clause-with-union-in-sql-server.html
hopefully it will resolve your issue will let you know complete details or union and order by statement.

Not able to populate a table from the output of a function

I am unable to populate my table from the output of my function. I have three columns in my table namely, EmpId,Dates,EmpName. The columns EmpId and EMpName are static values which are getting populated fine but the column Dates has to be populated through a function. However, when I try to do the same I am getting a syntax error.
Please Find below the query I am using
INSERT INTO Dbo.LeaveDates (EmpId,[Date],EmpName) VALUES(#EmpId,MyDate,#Emp_Name)
Select MyDate from [dbo].[ListDates](CONVERT(CHAR, #FromDate),CONVERT(CHAR, #ToDate))
The error I am getting is also under:
*The name "MyDate" is not permitted in this context. Valid expressions are constants, constant expressions, and (in some contexts) variables.
Column names are not permitted.
*
I have declared all variables in question
What am I doing wrong?
You have to do it this way:
INSERT INTO Dbo.LeaveDates (EmpId,[Date],EmpName)
SELECT #EmpId, MyDate, #Emp_Name
FROM [dbo].[ListDates](CONVERT(CHAR, #FromDate),CONVERT(CHAR, #ToDate))
Your query consists essentially of two separate sql statements. An INSERT INTO:
INSERT INTO Dbo.LeaveDates (EmpId,[Date],EmpName)
VALUES(#EmpId,MyDate,#Emp_Name)
followed by a SELECT:
SELECT MyDate
FROM [dbo].[ListDates](CONVERT(CHAR, #FromDate),CONVERT(CHAR, #ToDate))
INSERT fails because, as the error message clearly states, MyDate is not permitted in this context, i.e. as a separate column name, without being selected from a table.

Select All as default value for Multivalue parameter

I'm building a report in Visual Studio 2008 with a lot of multivalue parameters and it's working great, but I would like to have have the "(Select all)" option as the default value when the report is opened.
Is there some kind of expression or SQL code I can use to make this happen? Or do I need to choose "(Select all)" every time, in every parameter, each time I want to run the report?
Try setting the parameters' "default value" to use the same query as the "available values". In effect it provides every single "available value" as a "default value" and the "Select All" option is automatically checked.
Using dataset with default values is one way, but you must use query for Available values and for Default Values, if values are hard coded in Available values tab, then you must define default values as expressions. Pictures should explain everything
Create Parameter (if not automaticly created)
Define values - wrong way example
Define values - correct way example
Set default values - you must define all default values reflecting available values to make "Select All" by default, if you won't define all only those defined will be selected by default.
The Result
One picture for Data type: Int
Does not work if you have nulls.
You can get around this by modifying your select statement to plop something into nulls:
phonenumber = CASE
WHEN (isnull(phonenumber, '')='') THEN '(blank)'
ELSE phonenumber
END
The accepted answer is correct, but not complete.
In order for Select All to be the default option, the Available Values dataset must contain at least 2 columns: value and label. They can return the same data, but their names have to be different. The Default Values dataset will then use value column and then Select All will be the default value. If the dataset returns only 1 column, only the last record's value will be selected in the drop down of the parameter.
Adding to the answer from E_8.
This does not work if you have empty strings.
You can get around this by modifying your select statement in SQL or modifying your query in the SSRS dataset.
Select distinct phonenumber
from YourTable
where phonenumber <> ''
Order by Phonenumber
It works better
CREATE TABLE [dbo].[T_Status](
[Status] [nvarchar](20) NULL
) ON [PRIMARY]
GO
INSERT [dbo].[T_Status] ([Status]) VALUES (N'Active')
GO
INSERT [dbo].[T_Status] ([Status]) VALUES (N'notActive')
GO
INSERT [dbo].[T_Status] ([Status]) VALUES (N'Active')
GO
DECLARE #GetStatus nvarchar(20) = null
--DECLARE #GetStatus nvarchar(20) = 'Active'
SELECT [Status]
FROM [T_Status]
WHERE [Status] = CASE WHEN (isnull(#GetStatus, '')='') THEN [Status]
ELSE #GetStatus END
This is rather easy to achieve by making a dataset with a text-query like this:
SELECT 'Item1'
UNION
SELECT 'Item2'
UNION
SELECT 'Item3'
UNION
SELECT 'Item4'
UNION
SELECT 'ItemN'
The query should return all items that can be selected.

Resources