SQL Server select from temp table into another temp table - sql-server-2008-r2

I have this in a stored procedure:
select * into #temp_UNION from
(
SELECT 6 AS InteractionType, * FROM history.GetHistoryRewardPointsForIncentiveOption (588,1,6)
UNION all
SELECT 8 AS InteractionType, * FROM history.GetHistoryRewardPointsForIncentiveOption (558,1,8)
) a
which gives:
interaction type historyid incentiveprogramid points
6 1 1 50
6 1 4 50
6 1 5 50
8 1 3 100
8 1 4 100
then i have:
select tu.InteractionType,ipc.Name,tu.Points from #temp_UNION tu
inner join Incentive.IncentiveProgramCultures ipc
on tu.IncentiveProgramId = ipc.IncentivePrograms_IncentiveProgramId
inner join Zinc.Users zu
on zu.Cultures_DefaultCultureId = ipc.IncentiveProgramCultureId
where zu.UserId = 588
6 India - Q2 Incentive 50
8 India - Q2 Incentive 100
now i need to make up HintText which is a field in my #CategoriesTable(previously defined) by using the name i got from above and the points
UPDATE #CategoriesTable
SET HintText = CASE WHEN HasAssessment = 1
THEN 'Program ' + tu.name + ' will earn you ' + tu.points
ELSE 'With No Assessment'
END
but i get an error on tu.Name: multi part identifier could not be bound?
how can i achieve? should i make use of another temp table with the 2 rows in it?
here new code:
select * into #temp_UNION from
(
SELECT 6 AS InteractionType, * FROM history.GetHistoryRewardPointsForIncentiveOption (588,1,6)
UNION all
SELECT 8 AS InteractionType, * FROM history.GetHistoryRewardPointsForIncentiveOption (558,1,8)
) a
select tu.InteractionType,ipc.Name,tu.Points,zu.UserId into #temp1 from #temp_UNION tu
inner join Incentive.IncentiveProgramCultures ipc
on tu.IncentiveProgramId = ipc.IncentivePrograms_IncentiveProgramId
inner join Zinc.Users zu
on zu.Cultures_DefaultCultureId = ipc.IncentiveProgramCultureId
where zu.UserId = 588
Select * from #temp1 t
UPDATE #CategoriesTable
SET HintText = CASE WHEN HasAssessment = 1
THEN 'Program ' + t.Name + ' and points = ' + t.Points
ELSE 'With No Assessment'
END
FROM #temp1 t
WHERE t.userId = #CategoriesTable.UserId
DROP TABLE #temp_UNION
DROP TABLE #temp1
SELECT *
FROM #CategoriesTable
im not getting the #CategoriesTable?

You must specify the "tu" alias in the update clause
UPDATE #CategoriesTable
SET HintText = CASE WHEN HasAssessment = 1
THEN 'Program ' + tu.name + ' will earn you ' + tu.points
ELSE 'With No Assessment'
END
FROM #temp_UNION tu
WHERE tu.? = #CategoriesTable.? --JOIN condition

Related

SQL adding numbers column

Let's say I have a table:
Table1
ID | Table2_ID | Title
1 1 Breaking_Bad
2 1 Breaking_Bad
3 2 Simpsons
4 1 House_Of_Cards
I want to rename the title by adding '_XX' (where XX is a number) to only to those entries that are the same title and have the same Table2_ID.
So end results would be
Table1
ID | Table2_ID | Title
1 1 Breaking_Bad_01
2 1 Breaking_Bad_02
3 2 Simpsons
4 1 House_Of_Cards
How could I do this with TSQL?
You can do this with
WITH T
AS (SELECT *,
COUNT(*) OVER (PARTITION BY Table2_ID, Title) AS Cnt,
ROW_NUMBER() OVER (PARTITION BY Table2_ID, Title ORDER BY ID) AS RN
FROM Table1)
UPDATE T
SET Title = Title + '_' + FORMAT(RN, 'D2')
WHERE Cnt > 1;
SQL Fiddle
Or if you are on a version without FORMAT
SET Title = Title + CASE WHEN RN < 10 THEN '_0' ELSE '_' END + CAST(RN AS VARCHAR(10))
Will this work in SQL Server? The padding to 2 digits would be straightforward.
UPDATE TABLE1 A SET TITLE = TITLE + '_' + (SELECT COUNT(*) FROM TABLE1 B WHERE A.TITLE=B.TITLE AND A.ID<=B.ID) WHERE A.ID IN (SELECT B.ID FROM TABLE1 B
WHERE A.Id<>B.ID and A.TITLE=B.TITLE)

get OBJECT_ID in linked server

Second select (from linked server) does not return any values.. Object_ID doesnt work. Is any workaround?
select '', name
FROM sys.databases
WHERE 1 = 1
AND NAME <> db_name() -- exclude current database
AND CASE
WHEN STATE = 0
THEN CASE
WHEN OBJECT_ID(NAME + '.dbo.tPA_SysParam', 'U') IS NOT NULL
THEN 1
END
END = 1
union
select '[LINKED]', name
FROM [LINKED].master.sys.databases
WHERE 1 = 1
AND CASE
WHEN STATE = 0
THEN CASE
WHEN OBJECT_ID('[LINKED].'+NAME + '.dbo.tPA_SysParam', 'U') IS NOT NULL
THEN 1
END
END = 1
You can also mimic OBJECT_ID with a little help from the PARSENAME function:
Declare #FullTableName nvarchar(max) = '[dbo].[MyTable]';
Select t.object_id
From [LINKED].MyDatabase.sys.tables As t
Inner Join [LINKED].MyDatabase.sys.schemas As s On t.schema_id = s.schema_id
Where t.[name] = PARSENAME(#FullTableName, 1)
And s.[name] = PARSENAME(#FullTableName, 2)

How do I join two tables with different column in SQL Server CE?

How can I joining two tables with different column in SQL Server CE?
I have two tables:
Table Schedule
+-----+----------+------+
+ ID + Name + Type +
+-----+----------+------+
+ 1 + A + 1 +
+ 2 + B + 1 +
+ 3 + C + 2 +
+-----+----------+------+
Table Description
+-----+--------------------+
+ ID + Description +
+-----+--------------------+
+ 1 + A1 - XXXXX +
+-----+--------------------+
And what I want to get is the table like:
+-----+----------+-----------------+
+ ID + Name + Description +
+-----+----------+-----------------+
+ 1 + A + A1 - XXXXX +
+ 2 + B + - +
+ 3 + C + - +
+-----+----------+-----------------+
Where the Description column should be filled in by - when the ID is not on the Description table.
I tried this code:
SELECT S.ID, D.Description
FROM Schedule AS S
INNER JOIN Description AS D
But resulted in:
+-----+----------+-----------------+
+ ID + Name + Description +
+-----+----------+-----------------+
+ 1 + A + A1 - XXXXX +
+ 2 + B + A1 - XXXXX +
+ 3 + C + A1 - XXXXX +
+-----+----------+-----------------+
And when I tried to give ON Clause:
SELECT S.ID, D.Description
FROM Schedule AS S
INNER JOIN Description AS D ON S.ID = D.ID
It just get the row where the ID is on the Description table, like:
+-----+----------+-----------------+
+ ID + Name + Description +
+-----+----------+-----------------+
+ 1 + A + A1 - XXXXX +
+-----+----------+-----------------+
How can I do that?
[UPDATE]
I tried this code and it works:
SELECT S.ID, S.Name, COALESCE (D.Description, '-') AS Description
FROM Schedule AS S
LEFT OUTER JOIN Description AS D ON S.ID = D.ID
But now, how can I add a WHERE clause on it (pls see table SCHEDULE above)?
I tried:
SELECT S.ID, S.Name, COALESCE (D.Description, '-') AS Description
FROM Schedule AS S
LEFT OUTER JOIN Description AS D ON S.ID = D.ID AND S.Type = '1'
But still get the whole rows.
LEFT OUTER JOIN in SQL Server CE
You need to use LEFT OUTER JOIN to join the tables Schedule and Description on the key field ID. Also, use COALESCE to replace NULL values in Description column with -
Script:
SELECT S.ID
, S.Name
, COALESCE (D.Description, '-') AS Description
FROM Schedule AS S
LEFT OUTER JOIN Description AS D
ON S.ID = D.ID
Output:
Tested in Microsoft SQL Server CE version 4.0.8482.1
With WHERE clause
You need add the WHERE clause after the JOINs. If you are planning to having an ORDER BY, it should come after the WHERE clause.
Script:
SELECT S.ID
, S.Name
, COALESCE (D.Description, '-') AS Description
FROM Schedule AS S
LEFT OUTER JOIN Description AS D
ON S.ID = D.ID
WHERE (S.Type = 1)
Output:
Tested in Microsoft SQL Server CE version 4.0.8482.1
You need LEFT OUTER JOIN.
SQLFiddle: http://sqlfiddle.com/#!3/7dccf/1
Query:
select s.ID, s.Name, Coalesce(d.description,'-') as description
from schedule s
left outer join description d on d.id = s.id
SELECT S.ID, D.Description
FROM Schedule AS S FULL OUTER JOIN Description AS D
ON S.ID = D.ID
INNER JOIN means select only rows that exist in both tables.
FULL OUTER JOIN means select rows as long as they exist in one table.
You need FULL OUTER JOIN...
You need to use an OUTER JOIN instead of INNER, and use IsNull or Coalesce to replace NULL values:
SELECT S.ID, Coalesce(D.Description , '-') AS Description
FROM Schedule AS S FULL OUTER JOIN Description AS D
ON S.ID = D.ID

Need to pivot or crosstab a table but not in the conventional way. please

I have a small situation here.. hope you guys can help me out.
I'm supposed to query a table wich has 4 columns
AccountNo, ResourceNo, ProductNo, CustomerNo.
A few accountNo's have 2 ResourceNo's (115 and 134)
I have to Query it in such a way that I have to show two dynamic columns for the resourceNo values and put an 'X' against the accountNo which has those ResourceNo's.. So that the AccountNo is not repeated.. Pivoting doesn't help in this situation. Please look into this and help me.
See also
Poor Man's SQL Pivot.
See also
Sql Pivot Query with Dynamic Columns
You need poor man's pivot:
Poor Man's SQL Pivot. List Questions as Columns and Answers per User in one row
Static Columns
For example:
select
AccountNo,
case when sum(case when ResourceNo = 134 then 1 else 0 end) = 0 then '' else 'X' end as Resource_134,
case when sum(case when ResourceNo = 115 then 1 else 0 end) = 0 then '' else 'X' end as Resource_115
from
AccountResource
group by
AccountNo
Example Data:
AccountNo ResourceNo ProductNo CustomerNo
A1 134 P1 C1
A1 134 P2 C1
A1 134 P3 C2
A2 134 P1 C1
A2 115 P1 C4
A2 115 P2 C1
A3 115 P5 C2
Example output:
AccountNo Resource_134 Resource_115
A1 X
A2 X X
A3 X
Dynamic Columns
For dynamic columns you can do this:
declare #sql nvarchar(max)
set #sql = ''
select #sql = #sql + ',' + char(13)+char(10)+
'case when sum(case when ResourceNo = ''' + replace(cast(ResourceNo as nvarchar(10)), '''', '''''') + ''' then 1 else 0 end) = 0 then '''' else ''X'' end as "Resource_' + replace(cast(ResourceNo as nvarchar(10)), '"', '""') + '"'
from AccountResource
group by ResourceNo
order by Resourceno
set #sql = 'select AccountNo' + #sql
+ char(13)+char(10)
+ 'From AccountResource '
+ char(13)+char(10)
+ 'group by AccountNo'
+ char(13)+char(10)
+ 'order by AccountNo'
select * from datacheck.dbo.splitmax(#sql, null,null)
exec sp_executesql #sql

Get index of row within a group?

I have two tables:
Unit:
UnitId int PK
Title varchar
UnitOption:
UnitOptionId int PK
UnitId int FK
Title varchar
Quote:
QuoteId int PK
UnitOptionId int FK
Title varchar
I want to create a scalar UDF that takes a QuoteId param and returns a varchar that contains the following description (pseudu):
Quote.Title + '-' + Unit.Title + '-' + Unit.UnitId +
/* Here is where my question is:
If there are more than 1 UnitOption under this Unit, then
return '-' + the UnitOption number under this Unit
(i.e.) if under this Unit, there are 3 UnitOption with IDs 13, 17, 55
under the unit, and the current Quote.UnitOptionId is the 17 one,
it should return 2.
Which means I want to retrieve an ID of this row in the group.
Else
return ''
*/
If you're using SQL 2005 or later and I've interpreted your question correctly, you should be able to adapt the following into your function.
WITH [UnitExt] AS
(
SELECT
[Unit].[UnitId],
[Unit].[Title],
COUNT(*) AS [Count]
FROM [Unit]
INNER JOIN [UnitOption] ON [UnitOption].[UnitId] = [Unit].[UnitId]
GROUP BY
[Unit].[UnitId],
[Unit].[Title]
)
SELECT
[Quote].[Title] + '-' + [UnitExt].[Title] + '-' + [UnitExt].[UnitId] +
CASE
WHEN [UnitExt].[Count] > 1 THEN '-' +
CAST([UnitOption].[UnitOptionId] AS varchar(max))
ELSE ''
END
FROM [Quote]
INNER JOIN [UnitOption] ON [UnitOption].[UnitOptionId] =
[Quote].[UnitOptionId]
INNER JOIN [UnitExt] ON [UnitExt].[UnitId] = [UnitOption].[UnitId]
WHERE [Quote].[QuoteId] = #QuoteId
Something like this should do it.
SELECT DISTINCT Quote.Title +
' - ' + Unit.Title +
' - ' + Unit.UnitId +
CASE
WHEN COUNT(*) OVER(PARTITION BY Quote.Id) > 0
THEN
' - ' + CAST(ROW_NUMBER() OVER (PARTITION BY Quote.Id ORDER BY Quote.UnitOptionId) AS varchar)
ELSE
''
END
FROM Quote
JOIN UnitOption ON UnitOption.Id = Quote.UnitOptionId
JOIN Unit ON Unit.Id = UnitOption.UnitId
WHERE Quote.Id = #QuoteId
CREATE FUNCTION ufnGetDescription
(#QuoteID INT)
RETURNS VARCHAR(MAX)
AS
BEGIN
DECLARE #RetVal VARCHAR(MAX);
WITH CurRow
AS (SELECT quote.title + '- ' + unit.title AS start,
u.unitid,
quoteid,
uo.unitoptionid
FROM quote
INNER JOIN unitoption uo
ON quote.unitoptionid = uo.unitoptionid
INNER JOIN unit
ON uo.unitid = unit.unitid
WHERE quote.quoteid = #QuoteID),
AllUnits
AS (SELECT u.unitid,
uo.unitoptionid,
Row_number()
OVER(PARTITION BY u.unitid ORDER BY uo.unitoptionid) AS NUMBER,
Count(* )
OVER(PARTITION BY u.unitid ) AS cntUnits
FROM unit
INNER JOIN unionoption uo
ON unit.unitid = uo.unitid
WHERE u.unitid IN (SELECT unitid
FROM CurRow))
SELECT #RetVal = CASE
WHEN a.cntUnits = 1 THEN ''
ELSE r.start + '-' + Cast(NUMBER AS VARCHAR(max))
END
FROM AllUnits a
INNER JOIN CurRow r
ON a.unitoptionid = r.unitoptionid
RETURN #RetVal
END