The multi-part identifier "company.ID" could not be bound - sql

This query breaks because I have a multipart identifier that could not be bound. I have searched around and have tried a few suggestions online and none of which work for me. I have made sure that there is no typing errors.
WITH TempResult AS
(
SELECT
ROW_NUMBER() OVER(ORDER BY RequestDate) as RowNum,
[BillSearchesId],
[RequestDate],
company.[ID] AS [CompanyId],
users.ID AS [UserID],
[DeedsOffice],
[Description],
[DocNo],
[MicrofilmRefNumber],
[UserReference],
[USERNAME],
[TextCopyRequest],
[NotFound],
STUFF ((SELECT ', ' + CAST([FormatId] AS VARCHAR(20))
FROM [dbo].[DeedsDocumentCopyLocations] ddcl
WHERE ddcl.DocumentCopyId = ddcr.DocumentCopyId
FOR XML PATH('')), 1, 1, '') AS [FormatsAvailable]
FROM
[dbo].[DocumentCopyRequestsTable] ddcr
INNER JOIN
[dbo].[DocumentCopiesTable] ddc ON ddc.id = ddcr.DocumentCopyId
INNER JOIN
[dbo].[USERSTable] users ON users.ID = ddcr.UserId
INNER JOIN
[dbo].[COMPANYTable] company ON company.ID = ddcr.CompanyId
)
SELECT TOP (#LastRec-1) *
FROM TempResult
WHERE RowNum > #FirstRec
AND company.ID = #companyID // The multi-part identifier "company.ID" could not be bound.
AND RowNum < #LastRec
AND DocNo LIKE ISNULL(#DocumentNumber + '%',DocNo)
AND [Description] LIKE ISNULL(#Description + '%',[Description])
AND UserReference LIKE ISNULL(#Reference + '%', UserReference)

There's no table or table alias Company in that SELECT after your CTE - you cannot reference a table that isn't part of your SELECT ....
But that company.ID is available from the CTE already - just use that!
WITH TempResult AS
(
SELECT
....
company.[ID] AS [CompanyId], -- this defines a column "CompanyId" in your CTE
....
FROM
....
)
SELECT TOP (#LastRec-1) *
FROM TempResult
WHERE RowNum > #FirstRec
-- use the "CompanyID" column from your "TempResult" CTE .....
AND CompanyId = #companyID
......

Related

Increment values by column into rows-- SQL Server [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I have the following type of data
CREATE TABLE #tmp
(
Room [NVARCHAR](50) NOT NULL,
iking INT,
iqueen INT,
isingle INT,
idouble INT
)
INSERT INTO #tmp
VALUES ('Marriot', 0, 1, 2, 1),
('Hilton', 1, 2, 0, 1)
I tried Cross Apply and case statements
I add data into temp table and wrote 4 cross apply functions for each column
King
SELECT tk.Room, tk.iking, Type = CONCAT('BED', t.n)
INTO #tempking1
FROM #tmp tk
CROSS APPLY
(SELECT TOP (tk.iking)
n = ROW_NUMBER() OVER (ORDER BY o.object_id)
FROM sys.objects o) t
ORDER BY tk.Room;
--select * from #tempking1
Queen
SELECT
tq.Room, tq.iQueen,
Type = CASE WHEN ROOM in (SELECT Distinct ROOM FROM #tempking1)
THEN CONCAT('BED', t.n + 1)
ELSE CONCAT('BED', t.n)
END
INTO #tempQueen1
FROM #tmp tq
CROSS APPLY
(SELECT TOP (tq.iQueen)
n = ROW_NUMBER() OVER (ORDER BY o.object_id)
FROM sys.objects o) t
ORDER BY tq.Room;
--select * from #tempqueen1
Single
SELECT
tq.Room, tq.isingle,
Type = CASE WHEN ROOM IN (SELECT Distinct ROOM FROM #tempking1)
THEN CONCAT('BED', t.n + 1)
WHEN ROOM IN (SELECT Distinct ROOM FROM #tempqueen1)
THEN CONCAT('BED', t.n + 1)
ElSE CONCAT('BED', t.n)
END
INTO #tempsingle1
FROM #tmp tq
CROSS APPLY
(SELECT TOP (tq.isingle)
n = ROW_NUMBER() OVER (ORDER BY o.object_id)
FROM sys.objects o) t
ORDER BY tq.Room;
--select * from #tempsingle1
Double
SELECT
tq.Room, tq.isingle,
Type = CASE WHEN ROOM IN (SELECT Distinct ROOM FROM #tempking1)
THEN CONCAT('BED', t.n + 1)
WHEN ROOM IN (SELECT Distinct ROOM FROM #tempqueen1)
THEN CONCAT('BED', t.n + 1)
WHEN ROOM IN (SELECT Distinct ROOM FROM #tempsingle1)
THEN CONCAT('BED', t.n + 1)
ELSE CONCAT('BED', t.n)
END
INTO #tempdouble1
FROM #tmp tq
CROSS APPLY
(SELECT TOP (tq.isingle)
n = ROW_NUMBER() OVER (ORDER BY o.object_id)
FROM sys.objects o) t
ORDER BY tq.Room;
--select * from #tempDouble1
SELECT Room, Type, 'King' AS Descp FROM #tempKing1
UNION ALL
SELECT Room, Type, 'Queeen' AS Descp FROM #tempQueen1
UNION ALL
SELECT Room, Type, 'Single' AS Descp FROM #tempsingle1
UNION ALL
SELECT Room, Type, 'Double' AS Descp FROM #tempDouble1
but I got
My excepted output is
Could you please help me
You can use UNPIVOT operator to fix your solution. Try this script:
drop TABLE #tmp
go
drop TABLE #Hotel
go
CREATE TABLE #tmp
(
Room nvarchar(30) NOT NULL
,iking int
,iqueen int
,isingle int
,idouble int
)
CREATE TABLE #Hotel
(
Room NVARCHAR(30)
,RoomType NVARCHAR(30)
,Total INT
)
Insert into #tmp Values ('Marriot', 0,1,2,1),('Hilton', 1,2,0,1)
INSERT INTO #Hotel
SELECT Room, RoomType, Total
FROM
(SELECT Room,iking,iqueen,isingle,idouble
FROM #tmp) p
UNPIVOT
(Total FOR RoomType IN
(iking,iqueen,isingle,idouble)
)AS unpvt
SELECT Room
,RoomType
--,'Bed'+CAST(Number AS VARCHAR) AS [Desc]
,'Bed'+CAST(ROW_NUMBER() OVER(PARTITION BY Room ORDER BY RoomType,Number) AS VARCHAR) AS [Desc]
,'Bed'+CAST(Total AS varchar) [Desc2]
FROM #Hotel
INNER JOIN master.dbo.spt_values N ON Total>=N.Number AND N.type='P' AND number<>0

Types don't match between the anchor and the recursive part in column "ColumnName" of recursive query "CTE"

Trying to replicate Concatenation of multiple rows into one string-->https://www.red-gate.com/simple-talk/sql/t-sql-programming/concatenating-row-values-in-transact-sql/#Toc205129485
here is the query:
WITH CTE (id, CodeList, Code, Length)
AS (SELECT CAST(d.id AS NVARCHAR(MAX)) AS Id,
CAST('' AS NVARCHAR(MAX)) AS CodeList,
CAST('' AS NVARCHAR(MAX)) AS Code,
0 AS Length
FROM Letters d
INNER JOIN Cat c
ON c.ID = Cat_Sub
GROUP BY d.id
UNION ALL
SELECT CAST(dp.id AS NVARCHAR(MAX)) AS Id,
CAST(
CAST(CodeList AS NVARCHAR(MAX))
+ CASE
WHEN CAST(Length AS NVARCHAR(MAX)) = CAST('0' AS NVARCHAR(MAX)) THEN
CAST('' AS NVARCHAR(MAX))
ELSE
CAST(', ' AS NVARCHAR(MAX))
END
?????+ CAST(cp.Code AS NVARCHAR(MAX))??????
AS NVARCHAR(MAX)
) AS CodeList,
CAST(c.Code AS NVARCHAR(MAX)) AS Code,
c.Length + 1
FROM CTE c
INNER JOIN Letters dp
ON c.id= dp.id
INNER JOIN Cat cp
ON cp.ID = dp.id
WHERE cp.Code > c.Code
)
SELECT *
FROM CTE;
Msg 240, Level 16, State 1, Line 1 Types don't match between the
anchor and the recursive part in column "CodeList" of recursive query
"CTE".
I know this is a very often asked question but I can't get from where I get my error.
After testing I discovered that it comes when I add a piece of code in between question marks.
It has been casted but it still gives an error
Finally, I have solved the problem with another logic:
WITH Ranked ( CategoryId, rnk, ProductName )
AS ( SELECT CategoryId,
ROW_NUMBER() OVER( PARTITION BY CategoryId ORDER BY CategoryId ),
CAST( ProductName AS VARCHAR(8000) )
FROM Northwind..Products),
AnchorRanked ( CategoryId, rnk, ProductName )
AS ( SELECT CategoryId, rnk, ProductName
FROM Ranked
WHERE rnk = 1 ),
RecurRanked ( CategoryId, rnk, ProductName )
AS ( SELECT CategoryId, rnk, ProductName
FROM AnchorRanked
UNION ALL
SELECT Ranked.CategoryId, Ranked.rnk,
RecurRanked.ProductName + ', ' + Ranked.ProductName
FROM Ranked
INNER JOIN RecurRanked
ON Ranked.CategoryId = RecurRanked.CategoryId
AND Ranked.rnk = RecurRanked.rnk + 1 )
SELECT CategoryId, MAX( ProductName )
FROM RecurRanked
GROUP BY CategoryId;

Improve performance of SQL query with a FOR XML PATH in SQL Server 2008

I am trying to concatenate LoadIds for a user using For XML path which is a portion of my whole query, I verified that the maximum time gets elapsed in calculating this concatenated LoadId column. Below is the syntax, can anyone suggest a way to rewrite this efficiently?
SELECT
Col1, col2,
LoadIds = STUFF((SELECT ' , ' + CAST([LoadId] AS varchar(5))
FROM Table1 AS t1
WHERE t1.[UserId] = [t2].[UserId]
FOR XML PATH ('')), 1, 2, '')
FROM
Table1 AS t2
GROUP BY
[UserId]
1). I would try to collect the required data in a temp table or table variable, create an index on it and then play with the concatination.
2). FOR XML PATH works good for small sets of records, for large sets I would try a recursion.
declare #T table (
UserId int not null,
RowNumber int not null,
LoadId varchar(5) not null
primary key clustered (UserId, RowNumber)
);
insert into #T
select
UserId,
row_number() over(partition by UserId order by LoadId),
CAST(LoadId AS varchar(5))
from
Table1 ;
with cte (UserId, RowNumber, LoadIds) as
(
select
UserId,
RowNumber,
LoadIds = convert(varchar(8000), LoadId)
from #T
where RowNumber = 1
union all
select
t.UserId,
t.RowNumber,
convert(varchar(8000), cte.LoadIds + ', ' + t.LoadId)
from
cte inner join #T t on t.UserId = cte.UserId and t.RowNumber = cte.RowNumber + 1
)
select UserId, LoadIds = max(LoadIds) from cte group by UserId;
One thing you can do is select the distinct user ids before doing the string aggregation:
SELECT t2.UserId,
STUFF((SELECT ' , ' + CAST([LoadId] AS varchar(8000))
FROM Table1 t1
WHERE t1.[UserId] = [t2].[UserId]
FOR xml PATH ('')
), 1, 2, ''
) as LoadIds
FROM (SELECT DISTINCT userId
FROM Table1 t2
) t2;
For performance, an index on table1(UserId, LoadId) would also help.

How to incement row id with identity to off

I am getting this error while i do select.
DECLARE #TopID INT
SELECT #TopID = MAX([QuestionId]) from [SurveyQuestions];
SELECT
#TopID = #TopID + 1
,[questiontext]
,[DeptID]
,[SurveyID]
FROM [SOSS].[dbo].[SurveyQuestions] where surveyid =80
A SELECT statement that assigns a value to a variable must not be
combined with data-retrieval operations.
I know there is a posibility to fix this error with identity set to ON.but i dont want that as my db is hosted in legecy application, changing this will make other things to break.
This has nothing to do with the identity. It has to do with the select. You have:
SELECT #TopID = #TopID + 1,
[questiontext], [DeptID], [SurveyID]
FROM [SOSS].[dbo].[SurveyQuestions]
WHERE surveyid = 80
This has an assignment and it returns values. I think you really want:
SELECT #TopId + (ROW_NUMBER() OVER (ORDER BY (SELECT NULL))) as rownum,
[questiontext], [DeptID], [SurveyID]
FROM [SOSS].[dbo].[SurveyQuestions]
WHERE surveyid = 80;
Note: If you actually want the results in a particular order, then add an ORDER BY both to the query and to the ROW_NUMBER().
It is the way you are selecting, you cant use operators in select with other columns being fetched. See this link for some explanation on what you are doing wrong.
I think what you really require is this :
DECLARE #TopID INT
SELECT #TopID = MAX([QuestionId]) from [SurveyQuestions];
SELECT
#TopID + 1
,[questiontext]
,[DeptID]
,[SurveyID]
FROM [SOSS].[dbo].[SurveyQuestions] where surveyid =80
EDIT :
Or a ROW_NUMBER based solution like :
DECLARE #TopID INT
SELECT #TopID = MAX([QuestionId]) from [SurveyQuestions];
SELECT
#TopID + ROW_NUMBER() OVER (ORDER BY (SELECT 1)) as TopID
,[questiontext]
,[DeptID]
,[SurveyID]
FROM [SOSS].[dbo].[SurveyQuestions] where surveyid =80
Improving a bit on the Previous Answer (combined into one query):
SELECT (
SELECT TOP 1 QuestionId
FROM SurveyQuestions
ORDER BY QuestionId DESC
)
+ ROW_NUMBER() OVER ( ORDER BY (SELECT 1)) AS TopID
, [questiontext], [DeptID], [SurveyID]
FROM [SOSS].[dbo].[SurveyQuestions]
WHERE surveyid = 80
SQL Fiddler
Another Alternative, combing your 2 queries :
SELECT
(SELECT MAX(ID) FROM ForgeRock) as MAx_Id
, ROW_NUMBER() OVER (ORDER BY (SELECT 1)) as Row_ID,
(SELECT TOP 1 ID FROM ForgeRock ORDER BY Id DESC) +
ROW_NUMBER() OVER (ORDER BY (SELECT 1)) as New_Id,
productName,
description
FROM
ForgeRock
SQL Fiddler

initialize and increment variable inside cte query sqlserver 2008

I am using sqlserver 2008 ,I want to initialize and increment variable (#NUMTwo) both at the same time, in my second part(Problem Line).
I am creating a cte query.
Is this possible , if yes then please let me know.
following is a sample example.I hope i am clear.
CREATE table #TempTable
(
childProductID INT,parentProductID INT,productModel varchar(50),[Num2] VARCHAR(100)
)
DECLARE #NUMTwo INT = 0
WITH tableR AS
(
-- First Part
SELECT childProductID = null,parentProductID=null,productModel from Products where productid in (#a),[Num2] = convert(varchar(100), '')
UNION ALL
--Second Part
SELECT e.childProductID,e.parentProductID,prd.productModel FROM ProductIncludes AS e
,[Num2] = convert(varchar(100),'1.' + #NUMTwo+=1 ) -- Problem line
INNER JOIN Products AS PRD ON e.childProductID = PRD.productID
WHERE parentProductID in (#a)
)
INSERT INTO #TempTable(childProductID,parentProductID,productModel,[Num2])
SELECT childProductID,parentProductID,productModel,[Num2]
END
SELECT * FROM #TempTable
You need to "Initialize" a column in the acnhor part of the query, and then "oncrement" this column in the recursive parts.
Something like
DECLARE #NUMTwo INT = 0
;WITH Test AS (
SELECT [Num2] = convert(varchar(MAX), ''),
#NUMTwo [N]
UNION ALL
SELECT [Num2] = '1.' + convert(varchar(MAX),[N]+1),
[N]+1
FROM TEst
WHERE [N] < 10
)
SELECT *
FROM Test
SQL Fiddle DEMO
If the parameter #NUMTwo is just for numbering rows you can use the ROW_NUMBER() OVER(...) instead of it like so:
WITH tableR AS
(
SELECT childProductID = NULL, parentProductID = NULL,
productModel, NUMTwo = CAST('0' AS VARCHAR(10))
FROM Products
WHERE
productid in (#a),
[Num2] = convert(varchar(100), '')
UNION ALL
SELECT e.childProductID, e.parentProductID,
prd.productModel,
NUMTwo = '1.' +
CAST( ROW_NUMBER() OVER(ORDER BY (SELECT 0)) AS VARCHAR(10))
FROM ProductIncludes AS e
INNER JOIN Products AS PRD ON e.childProductID = PRD.productID
WHERE parentProductID in (#a)
)