SQL field data addition - sql

I am just wondering if it is possible to do something and as I cannot find any information about it:
let's say I have a field that I want to concatenate values to it:
For example
table 'test'
id | name |  surname
01 |  georges |  Michael
and I am trying to add information about this field like :
table 'test'
id | name | surname
01 | georges, rick | Michael
Do I need to update, insert or alter this 'test'.'name' with a second value(in this case 'rick')? Is it even possible to do that or will I need to create another related table in order to link 'rick' with 'georges'?
I know that if it is possible I will have to "insert" the comma as well but I do not know how.

SQL Server:
UPDATE test SET name = name + ', Rick' WHERE id = '01'
If you need to pull Rick from another table, you could do something like this:
UPDATE t
SET t.name = t.name + ', ' + o.othername
FROM test t
JOIN othername o ON t.id = o.id
WHERE t.id = '01'
And if you were looking for further posts/info on the topic, I'd suggest googling sql server string concatenation

Related

how to insert using join in query

i have a table like this
registrationId | standardId | courseId | marks
===============================================
5001 | 1 | 1 | 67
5001 | 1 | 2 | 87
and so on my question is the standard name and course name come from different tables so while updating i have to use 3 diffent queries 1st to get standardId according to standard name courseid acording to coursename and later update into this table. can it be done in one query?
Punctuation exists for a reason; you should use it. Without it, such a long sentence is difficult to read and understand.
Title says "insert", body says "update"; which one is it?
For UPDATE, something like this might do what you need:
update this_table tt set
tt.standardid = (select s.standardid
from standard s
where s.standard_name = :some_unique_standard_name
),
tt.courseid = (select c.courseid
from course c
where c.course_name = :some_unique_course_name
)
where tt.registrationid = :some_registration_id;
For INSERT:
insert into this_table
(registrationid, standardid, courseid, marks)
select
:some_registration_id,
(select s.standardid
from standard s
where s.standard_name = :some_unique_standard_name
),
(select c.courseid
from course c
where c.course_name = :some_unique_course_name
),
:marks_value
from dual;
in both cases, subqueries must return a single value
colon (:) represents a variable whose value you need to provide
syntax is based on Oracle; your database might differ (especially for INSERT, as there's probably no DUAL table elsewhere).

Using the value of one field as the column name in a subquery

I am trying to work out a query in SQL to select records from a secondary table, based on an the answer to one of many fields. The particular field varies from record to record, so I need to use a VALUE from my initial query as a COLUMN title in my secondary query.
I have three table (simplified for this example)
Pass table:
PassID | PassType | PersonID |
1 | 3 | 54 |
2 | 4 | 59 |
Qualification Required Table:
PassType | QualificationField | QualificationAnswer
3 | Q8 | Yes
4 | Q3 | All
Person Table:
PersonID | Name |...| Q3 |...| Q8
54 | John |...| Non |...| No
59 | Jane |...| ALL |...| No
Essentially different passes have different criteria that qualifies them for something extra... What I need to determine is for each person, if they have the qualifying criteria based on the pass they have been assigned.
The tables are actually part of a much bigger system and columns in the person table can be added dynamically on different iterations of the database, so I can't significantly change the table structure - I need to be able to extract my answer in the SQL query to determine which people qualify for this 'something extra'.
I already have a query (Q_PersonWithPass) that matches the pass type and qualification requirements, to give me the following fields in one output:
PersonID | PassType | QualificationField | QualificationAnswer
54 | 3 | Q8 | Yes
59 | 4 | Q3 | All
What I need to do now is run a subquery on the person table to look up the column based relating to the QualificationField answer, and check if that field in the Person table matches the QualificationAnswer.
I've tried this:
SELECT PersonID, PassType, QualificationField, QualificationAnswer,
(SELECT dbo.Q_PersonWithPass.QualificationField
FROM dbo.Person
WHERE (PersonID = dbo.Q_PersonWithPass.PersonID)) AS QualFld
FROM dbo.Q_PersonWithPass
Thus just displays "Q8" or "Q3" in the QualFld rather than the answer "No" or "All"
Is there a way I can get SQL to recognise the value from 'dbo.Q_PersonWithPass.QualificationField' as a column title rather than a variable in the subquery?
As mentioned in one of the comments under the answer I think the only way of doing what you want is by generating a dynamic sql query. The code below might not be keystroke perfect, but it should give you an idea of what to do.
The idea is that you work out all of the possible qualification fields, insert them into a temporary table, then build a case statement dynamically based on all of the available options.
Select Distinct QualificationField
Into #TEMPTABLE
From dbo.Q_PersonWithPass;
DECLARE
#SQLQuery nvarchar(4000),
#QField nvarchar(10)
BEGIN
Set #SQLQuery = 'select PWP.PersonId, PWP.PassType, PWP.QualificationField, PWP.QualificationAnswer, Case ';
While EXISTS(Select * from #TEMPTABLE)
Begin
Select Top 1 #QField = QualificationField From #TEMPTABLE;
Set #SQLQuery = #SQLQuery + 'When PWP.QualificationField = ' + #QField + ' Then P.' + #QFIELD + ' ';
Delete from #TEMPTABLE Where QualificationField = #QField;
End
Set #SQLQuery = #SQLQuery + ' end AS QualFld FROM dbo.Q_PersonWithPass PWP JOIN dbo.Person P on P.PersonID = PWP.PersonID';
EXECUTE sp_executesql #SQLQuery
END;
Let me know if you have any problems.
Not Sure what exactly you want as a result but you can achieve what you are trying to do by using CASE. Something along the lines of this:
SELECT PersonID, PassType, QualificationField, QualificationAnswer,
(CASE When p.PersonID = dbo.Q_PersonWithPass.PersonID then 'Yes'
else 'No' end ) ASQualFld
FROM dbo.Q_PersonWithPass LEFT JOIN Person p on p.PersonID = dbo.Q_PersonWithPass.PersonID

using multi-value parameter with delimited string in dataset

I have a table that contains a field with a delimited string, This is in fact a unsorted list of id's
id| name | valueslist
----------------------------------------------
1 | John | 46423423,36456325,76473234,98798796
2 | Mike | 36456325,98798796
3 | Sara | 46423423
I have a multi-value parameter based on a dataset that lists all possible id's
param: #chosenvalues
possible values:
46423423
36456325
76473234
98798796
Now, when selecting on or more id's in the parameter, I want to return all records from my table that have that value present in their valueslist.
eg:
If I select 36456325 I need John & Mike to be returned
If I select 46423423 I need John & Sara to be returned
If I select 46423423 & 98798796 I need all three to be returned
I thought I could solve this like
SELECT * FROM table WHERE '%' + valueslist + '%' IN ('%' + #chosenvalues + '%')
but that doesn't work. Any suggestions as to how I could solve this?
TIA,
Henro
edit: I know this is in fact far from ideal modeling but unfortunately it is what I have to work with.
Please try the following SQL Select statement
/*
create table valueslisttbl (id smallint, name varchar(20), valueslist varchar(1000))
insert into valueslisttbl values
(1, 'John', '46423423,36456325,76473234,98798796'),
(2, 'Mike', '36456325,98798796'),
(3, 'Sara', '46423423')
*/
declare #chosenvalues varchar(100)
--set #chosenvalues = '46423423'
--set #chosenvalues = '36456325'
--set #chosenvalues = '76473234'
set #chosenvalues = '46423423,98798796'
select distinct name
from valueslisttbl
cross apply dbo.Split(valueslisttbl.valueslist, ',') s
where s.val in (
select val from dbo.Split(#chosenvalues, ',')
)
Also note that you need a SQL Split function in order to solve your requirement
I used SQL XML for the above SQL Server split function where you can find the SQL source codes at http://www.kodyaz.com/articles/t-sql-convert-split-delimeted-string-as-rows-using-xml.aspx
I hope it helps,
And suddenly I was struck by lightning and the idea came to me in a blinding flash of genius. (Well, it FELT that way anyway)
I joined the table with john's and janes to the table with all the possible solutions. I then did a select distinct using a real standard where clause
SELECT DISTINCT j.*
FROM tableJohn j
LEFT JOIN Table_Solutions s on '%'+ s.value + '%' LIKE j.valuelist
WHERE s.value in (#chosen_values)
#chosen_values could now nicely be populated with values from a multi-value parameter in a SSRS report.

How to use a value of cell as a SELECT param in SQL SERVER

I have two tables.
1.TextLang Table:
| Key | En | Uk |
|'000'| 00 | 01 |
2.Users Table
| Id | Language |
|'11'| 'En' |
I want to create a query that get the Value from Users Table and use it as a select param to get a value from TextLang Table.
Example:
SELECT Value(Users.Language) FROM TextLang
INNER JOIN Users ON Users.Id='11'
WHERE Key='000'
Result:
| En |
| 00 |
So I expect Value(Users.Language) to be equals to 'En' And To get in this select the value 00
How would I do this? Thanks!
Something like this TSQL will work, but it's not pretty. Something that's relatively fast to come up with though.
Either way, as far as I know, you're going to have to build some kind of dynamic SQL to be able to do what you're trying to do. :)
DECLARE #SQL VARCHAR(MAX), #LAN_COLUMN VARCHAR(25)
SELECT #LAN_COLUMN = Language
FROM TextLang
JOIN Users ON Users.Id='11'
WHERE Key = '000'
SELECT #SQL =
'Select '+#LAN_COLUMN+' FROM TextLang '
+' JOIN Users ON Users.Id=''11'''
+' WHERE Key = ''000'''
EXEC(#SQL)

emulate group_concat in MSSQL, ambiguous column name?

I am currently trying to simulate the group_concat function in MySQL to MSSQL. I have followed code formats found in here and here. The problem is, when I try to execute the query, I get the message Ambiguous column name for my column RoleID. Here is my query:
select UserName, RoleID from tb_UserInRoles
cross apply(
select RoleName from tb_Roles
where tb_UserInRoles.RoleID = tb_Roles.RoleID
for XML Path('')
) fxMerge (RoleID) group by UserName, RoleID
I'd like to know why this particular code format present the Ambiguous column name error message. I need to make this query work and understand it. Thanks in advance for the help.
I plan on using this in a many-to-many relationship table, wherein users of a system can have multiple roles, like this:
| User | Role |
|--------|---------|
| JamesP | Maker |
| JamesP | Approver|
| JamesP | Admin |
I want the result query to be like this:
| User | Role |
|--------|--------------------------|
| JamesP | Maker, Approver, Admin |
Try this:
SELECT UIR.UserName, MAX(STUFF(fxMerge.RoleID, 1, 1, ''))
FROM tb_UserInRoles UIR
CROSS APPLY(
SELECT ',' + RoleName
FROM tb_UserInRoles UIR1
INNER JOIN tb_Roles RM ON UIR1.RoleID = RM.RoleID
WHERE UIR.UserName = UIR1.UserName
FOR XML PATH('')
) fxMerge (RoleID)
GROUP BY UIR.UserName