Invalid object name 'table1' - sql

DECLARE
#empid INT
, #schedindate DATETIME
, #ss NVARCHAR(100)
, #indice NVARCHAR(3)
, #FromDate DATETIME
, #ToDate DATETIME
, #TimeInR NVARCHAR(20)
, #TimeOutR DATETIME,#day nvarchar(3)
SELECT
#FromDate = '20090114'
, #ToDate = '20100130'
DECLARE #temp TABLE
(
schedindate DATETIME
, TimeInR VARCHAR(10)
, TimeOutR VARCHAR(10)
, empid INT
)
delete from PayrollTEST.dbo.[table1]
INSERT INTO #temp (schedindate, TimeInR, TimeOutR, empid)
SELECT DISTINCT
schedindate
, TimeInR
, TimeOutR
, empid
FROM dbo.ta_timecard
WHERE schedindate BETWEEN #FromDate AND #ToDate
DECLARE #ids TABLE(id BIGINT IDENTITY(1,1), emp BIGINT)
INSERT INTO #ids (emp)
SELECT DISTINCT empid
FROM #temp
INSERT INTO PayrollTEST.dbo.[table1](id, EmpID)
SELECT id, emp
FROM #ids
DECLARE cc CURSOR LOCAL FAST_FORWARD READ_ONLY FOR
SELECT DISTINCT empid
FROM #temp
OPEN cc
FETCH NEXT FROM cc INTO #empid
WHILE (##fetch_status = 0) BEGIN
SELECT
#indice = (select DATEDIFF(day,#fromdate, t.SchedInDate))
--, #TimeInR = t.TimeInR
, #schedindate = t.SchedInDate
, #day = dbo.ta_dayofweek(#schedindate)
FROM #temp t
WHERE empid = #empid
print(#indice)
print(#day)
print(#schedindate)
print(#TimeInR)
-- SELECT #ss = 'update table1 set nod' + #indice
-- + ' = '+ convert(nvarchar(3),#day) +' , din'
-- + #indice + ' = ' + #Schedindate + ' where empid = ' + CAST(#empid AS NVARCHAR(20))
SELECT #ss = 'update table1 set nod' + #indice
+ ' = '+ convert(nvarchar(3),#day) + ' where empid = ' + CAST(#empid AS NVARCHAR(20))
EXEC master.dbo.sp_executesql #ss
FETCH NEXT FROM cc INTO #empid
END
CLOSE cc
DEALLOCATE cc
Why am I getting this error? i'm in the right database and the table exist. I appreciate any help

Did you make sure that you are in the right database ?
you can run SELECT DB_NAME() to see your current databse

Related

Dynamic Database in SubQuery

SELECT
email, password,GP_employee_id, company,
(select distinct CHEKNMBR from [BSL].[dbo].[UPR30300] WHERE EMPLOYID = GP_employee_id and CHEKDATE > GETDATE() - 20 ) as slip_number,
(select distinct CONVERT(date , CHEKDATE) from [BSL].[dbo].[UPR30300] WHERE EMPLOYID = GP_employee_id and CHEKDATE > GETDATE() - 20 ) as slip_number
FROM [payslips].[dbo].[myapp_user]
I would like [BSL] to be dynamic. The value would depend on the company field of the main query. So I want something like this [company].[dbo].[UPR30300]
You can do one big dynamic UNION ALL query
DECLARE #unioned nvarchar(max) = (
SELECT STRING_AGG(CAST(
'
SELECT *, company = ' + QUOTENAME(company, '''') + '
FROM ' + QUOTENAME(company) + '.[dbo].[UPR30300]
WHERE CHEKDATE > DATEADD(day, -20, GETDATE())
'
AS nvarchar(max)), 'UNION ALL')
FROM (
SELECT DISTINCT company
FROM [payslips].[dbo].[myapp_user]
) au
);
DECLARE #sql nvarchar(max) = '
SELECT
au.email,
au.password,
au.GP_employee_id,
au.company,
slip_number = u.CHEKNMBR,
slip_number2 = CONVERT(date, u.CHEKDATE)
FROM [payslips].[dbo].[myapp_user] au
LEFT JOIN (
' + #unioned + '
) u ON u.company = au.company
AND u.EMPLOYID = au.GP_employee_id;
';
PRINT #sql; -- for testing
EXEC sp_executesql #sql;
DECLARE #sql VARCHAR(1000);
DECLARE #company VARCHAR(50);
DROP TABLE IF EXISTS #myapp_user;
CREATE TABLE #myapp_user
(
email VARCHAR(256),
[password] VARCHAR(256),
GP_employee_id INT,
slip_number INT,
slip_number2 INT
);
DECLARE db_cursor CURSOR FOR
SELECT DISTINCT company FROM [payslips].[dbo].[myapp_user];
OPEN db_cursor
FETCH NEXT FROM db_cursor INTO #company
WHILE ##FETCH_STATUS = 0
BEGIN
SET #sql = '
SELECT
email,
password,
GP_employee_id,
slip_number = (select distinct CHEKNMBR from ' + QUOTENAME(#company) + '.[dbo].[UPR30300] WHERE EMPLOYID = GP_employee_id and CHEKDATE > GETDATE() - 20),
slip_number2 = (select distinct CONVERT(date , CHEKDATE) from ' + QUOTENAME(#company) + '.[dbo].[UPR30300] WHERE EMPLOYID = GP_employee_id and CHEKDATE > GETDATE() - 20)
FROM
[payslips].[dbo].[myapp_user]';
INSERT INTO #myapp_user EXECUTE (#sql);
FETCH NEXT FROM db_cursor INTO #company;
END
CLOSE db_cursor
DEALLOCATE db_cursor
SELECT * FROM #myapp_user;

SQL Azure - The type of column "" conflicts with the type of other columns specified in the UNPIVOT list

we are migrating our Sql Server Stored Procedures to Sql Azure. We are getting below error when trying to create a Stored Procedure on Sql Azure
Error Message: Msg 8167, Level 16, State 1, Procedure
SP_Get_EmployeeGeneralDetails, Line 64 [Batch Start Line 6] The type
of column "EmployeeName" conflicts with the type of other columns
specified in the UNPIVOT list.
SP Script:
CREATE PROCEDURE [dbo].[SP_Get_EmployeeGeneralDetails]
(
#moduleID INT
,#templateID INT
,#employeeId INT
,#locationID INT
,#applicationID INT
,#culture NVARCHAR(20)
,#letterBody NVARCHAR(MAX) OUTPUT
)
WITH ENCRYPTION
AS
BEGIN
DECLARE #typeId INT
SELECT #typeId = TypeId
FROM tCultureMaster
WHERE CultureCode = #culture
DECLARE #symbolChangeTable TABLE
(
[Key] NVARCHAR(MAX)
,[Value] NVARCHAR(MAX)
)
INSERT INTO #symbolChangeTable
SELECT [Key]
,[Value]
FROM ( SELECT CONVERT(NVARCHAR(MAX), GETDATE(),107) AS [Date]
,CONVERT(NVARCHAR(MAX), ve.FullName) AS EmployeeName
--,ve.FullName AS EmployeeName ,CONVERT(NVARCHAR(MAX), ve.FullName) AS EmployeeName
,CASE #typeId
WHEN 1
THEN CONVERT(NVARCHAR(MAX), ve.Designation) /*English*/
ELSE CONVERT(NVARCHAR(MAX), ve.DesignationArabic) /*Arabic*/
END AS Designation --Column Name
,CASE #typeId
WHEN 1
THEN CONVERT(NVARCHAR(MAX), ve.Department) /*English*/
ELSE CONVERT(NVARCHAR(MAX), ve.DepartmentArabic) /*Arabic*/
END AS Department --Column Name
,CONVERT(NVARCHAR(MAX), l.CompanyName) AS CompanyName
,CONVERT(NVARCHAR(MAX), te.LastPromotionDate) AS LastPromotionDate
,CONVERT(NVARCHAR(MAX), veHr.FullName) AS HRAdmin
FROM tEmployee te
INNER JOIN dbo.v_Employees ve ON ve.EmployeeID = te.EmployeeId
INNER JOIN dbo.tLocation l ON l.LocationCode = te.LocationId
INNER JOIN dbo.v_Employees veHR ON veHR.EmployeeID = l.HRManager
WHERE te.EmployeeId = #employeeId
AND te.LocationId = #locationID
) pvt UNPIVOT
( [Value] FOR [Key] IN ( [Date], EmployeeName, Designation,
Department, CompanyName,
LastPromotionDate, HRAdmin
) ) AS unpvt
--Common Section for all Modules
DECLARE #body NVARCHAR(MAX)
SELECT #body = Body
FROM tLetterTemplates lt
WHERE TemplateID = #templateID
AND ModuleID = #moduleID
DECLARE #key NVARCHAR(MAX)
,#value NVARCHAR(MAX)
DECLARE cur_SymbolList CURSOR FOR SELECT [Key], [Value]
FROM #symbolChangeTable
OPEN cur_SymbolList
FETCH NEXT FROM cur_SymbolList INTO #key, #value
WHILE ##fetch_status = 0
BEGIN
SET #body = REPLACE(CAST(#body AS NVARCHAR(MAX)),
'#' + #key + '#', #value) ;
FETCH NEXT FROM cur_SymbolList INTO #key, #value
END
SET #letterBody = #body ;
--PRINT #body ;
--SELECT #body;
END
This stored Procedure gets created as correctly on Sql Server but gives error on SQL Azure.
All the columns in UnPivot have same type, NVARCHAR(MAX)
I can run this script in Azure SQL database and without any error. Please see the screenshot:
My Azure SQL database is version V12.0.2000.8. I didn't set anything just with the default settings.
The script is copy from you question:
CREATE PROCEDURE [dbo].[SP_Get_EmployeeGeneralDetails]
(
#moduleID INT
,#templateID INT
,#employeeId INT
,#locationID INT
,#applicationID INT
,#culture NVARCHAR(20)
,#letterBody NVARCHAR(MAX) OUTPUT
)
WITH ENCRYPTION
AS
BEGIN
DECLARE #typeId INT
SELECT #typeId = TypeId
FROM tCultureMaster
WHERE CultureCode = #culture
DECLARE #symbolChangeTable TABLE
(
[Key] NVARCHAR(MAX)
,[Value] NVARCHAR(MAX)
)
INSERT INTO #symbolChangeTable
SELECT [Key]
,[Value]
FROM ( SELECT CONVERT(NVARCHAR(MAX), GETDATE(),107) AS [Date]
,CONVERT(NVARCHAR(MAX), ve.FullName) AS EmployeeName
--,ve.FullName AS EmployeeName ,CONVERT(NVARCHAR(MAX), ve.FullName) AS EmployeeName
,CASE #typeId
WHEN 1
THEN CONVERT(NVARCHAR(MAX), ve.Designation) /*English*/
ELSE CONVERT(NVARCHAR(MAX), ve.DesignationArabic) /*Arabic*/
END AS Designation --Column Name
,CASE #typeId
WHEN 1
THEN CONVERT(NVARCHAR(MAX), ve.Department) /*English*/
ELSE CONVERT(NVARCHAR(MAX), ve.DepartmentArabic) /*Arabic*/
END AS Department --Column Name
,CONVERT(NVARCHAR(MAX), l.CompanyName) AS CompanyName
,CONVERT(NVARCHAR(MAX), te.LastPromotionDate) AS LastPromotionDate
,CONVERT(NVARCHAR(MAX), veHr.FullName) AS HRAdmin
FROM tEmployee te
INNER JOIN dbo.v_Employees ve ON ve.EmployeeID = te.EmployeeId
INNER JOIN dbo.tLocation l ON l.LocationCode = te.LocationId
INNER JOIN dbo.v_Employees veHR ON veHR.EmployeeID = l.HRManager
WHERE te.EmployeeId = #employeeId
AND te.LocationId = #locationID
) pvt UNPIVOT
( [Value] FOR [Key] IN ( [Date], EmployeeName, Designation,
Department, CompanyName,
LastPromotionDate, HRAdmin
) ) AS unpvt
--Common Section for all Modules
DECLARE #body NVARCHAR(MAX)
SELECT #body = Body
FROM tLetterTemplates lt
WHERE TemplateID = #templateID
AND ModuleID = #moduleID
DECLARE #key NVARCHAR(MAX)
,#value NVARCHAR(MAX)
DECLARE cur_SymbolList CURSOR FOR SELECT [Key], [Value]
FROM #symbolChangeTable
OPEN cur_SymbolList
FETCH NEXT FROM cur_SymbolList INTO #key, #value
WHILE ##fetch_status = 0
BEGIN
SET #body = REPLACE(CAST(#body AS NVARCHAR(MAX)),
'#' + #key + '#', #value) ;
FETCH NEXT FROM cur_SymbolList INTO #key, #value
END
SET #letterBody = #body ;
--PRINT #body ;
--SELECT #body;
END

How to find match of fullname (order doesn't matter) in sql For

For example: 'Swati Prakash Phapale' then possible condition are 'prakash swati phapale' , 'swati phapale prakash',prakash swati phapale' or multiple permutation
DECLARE #fName varchar(max) =ltrim(rtrim(isnull('swati','')))
DECLARE #mName varchar(max) =ltrim(rtrim(isnull(' phapale','')))
DECLARE #lName varchar(max) =ltrim(rtrim(isnull(' prakash','')))
DECLARE #FullName varchar(max), #Split char(1)=' ' ,#X1 xml,#i int=0
if len(#mName)!=0
set #FullName = #fName +' ' + #mName +' '+#lName
else
begin
set #FullName = #fName +' '+#lName
end
IF len(#FullName)=0 BEGIN
SET #FullName = 'null' END DECLARE #hit AS varchar(MAX)='',
#EmptyGuid UniqueIdentifier='00000000-0000-0000-0000-000000000000'
SELECT #X1 = CONVERT(xml,' <root> <s>' + REPLACE(#FullName,#Split,'</s> <s>') + '</s> </root> ')
declare #tmp1 as table(name varchar(max))
declare #tmp2 as table(RowNo bigint,name varchar(max))
insert into #tmp1(name)select * from (SELECT name = T.c.value('.','varchar(max)')FROM #X1.nodes('/root/s') T(c)) T
declare #num as int;
set #num = (select count(*) from #tmp1);
-- Permutations of #t
with T (name, level) as(select convert(varchar(max), name), level=1 from #tmp1 union all select convert(varchar(max),t1.name+' '+T.name),level+1
from #tmp1 t1,T where level < #num and charindex(t1.name,T.name) = 0)
insert into #tmp2(RowNo,name)select RowNo = Row_Number() over (order by name), name from T where level = #num
SET #hit= isnull((select tc.name from #tmp2 t inner join **YourTableName** tc on t.name=tc.name),'')
SET #hit=concat('Full Name Matched with:',#hit)
IF len(#hit)>0 --#hit<>''
SET #hit=concat('FullName Matched with:',#hit)
Else
BEGIN
SET #hit=concat('No FullName Matched with:',#hit)
end
print #hit
Note : In 'YourTableName', 'Name' column contain fullname

Adding values to an existing table by using Cursor

By running this code its working, but when I add more values to the table it's not working anymore. I appreciate any help, thank you.
This code works perfectly:
declare #id int
declare #empid int
set #id = 0
declare #schedindate datetime
declare #ss nvarchar(100)
declare #indice nvarchar(2)
declare #FromDate datetime
declare #ToDate datetime
declare #TimeInR datetime
declare #TimeOutR datetime
declare #departmentID int
declare #PositionID int
declare #BranchID int
declare #SupervisorID int
declare #GradeID int
declare #Custom1ID int
declare #Custom2ID int
declare #PayClassID int
declare #EmploymentType int
set #FromDate = '2009-01-14'
set #ToDate = '2010-01-30'
delete from table1
declare cc cursor for select distinct empid from ta_timecard where schedindate between #FromDate and #ToDate
open cc
fetch next from cc into #empid
while (##fetch_status = 0)
begin
set #id = #id + 1
insert into table1 (ID, EmpID) values (#id, #empid)
declare cc2 cursor for select distinct departmentid from ta_timecard where empid = #empid and schedindate between #FromDate and #ToDate
open cc2
fetch next from cc2 into #departmentID
while (##fetch_status = 0)
begin
set #indice = cast(datediff(day, #fromdate, #schedindate) as nvarchar(4))
set #ss = 'update table1 set departmetid = ' + convert(nvarchar(4), #departmentID)
+ ' where empid = ' + convert(nvarchar(4), #empid)
execute sp_executesql #ss
fetch next from cc2 into #departmentID
end
close cc2
deallocate cc2
fetch next from cc into #empid
end
close cc
Deallocate cc
GO
But when I add more values to the table I got the first row only affected
declare #id int
declare #empid int
set #id = 0
declare #schedindate datetime
declare #ss nvarchar(100)
declare #indice nvarchar(2)
declare #FromDate datetime
declare #ToDate datetime
declare #TimeInR datetime
declare #TimeOutR datetime
declare #departmentID int
declare #PositionID int
declare #BranchID int
declare #SupervisorID int
declare #GradeID int
declare #Custom1ID int
declare #Custom2ID int
declare #PayClassID int
declare #EmploymentType int
set #FromDate = '2009-01-14'
set #ToDate = '2010-01-30'
delete from table1
declare cc cursor for select distinct empid from ta_timecard where schedindate between #FromDate and #ToDate
open cc
fetch next from cc into #empid
while (##fetch_status = 0)
begin
set #id = #id + 1
insert into table1 (ID, EmpID) values (#id, #empid)
declare cc2 cursor for select distinct departmentid, branchid from ta_timecard where empid = #empid --and schedindate between #FromDate and #ToDate
open cc2
fetch next from cc2 into #departmentID, #BranchID--,#PositionID
while (##fetch_status = 0)
begin
set #indice = cast(datediff(day, #fromdate, #schedindate) as nvarchar(4))
set #ss = 'update table1 set departmetid = ' + convert(nvarchar(4), #departmentID)
+', branchid = ' + convert(nvarchar(4), #BranchID)
--+ ', positionid = ' + convert(nvarchar(4), #PositionID)
+ ' where empid = ' + convert(nvarchar(4), #empid)
print(#ss)
execute sp_executesql #ss
fetch next from cc2 into #departmentID, #BranchID--, #PositionID
end
close cc2
deallocate cc2
fetch next from cc into #empid
end
close cc
Deallocate cc
GO
Edited:
this is the table ta_TimeCard
you need check #BranchID on NULL values
+ ISNULL(', branchid = ' + convert(nvarchar(4), #BranchID), '')
Please change your query from
set #ss = 'update table1 set departmetid = '
to
set #ss = 'update table1 set departmentid = '
the n might affect your result

Cursorfetch:The number of variables declared in the INTO list must match that of selected columns

declare #id int
declare #empid int
set #id = 0
declare #schedindate datetime
declare #ss nvarchar(100)
declare #indice nvarchar(2)
declare #FromDate datetime
declare #ToDate datetime
declare #TimeInR datetime
declare #TimeOutR datetime
set #FromDate = '2009-01-14'
set #ToDate = '2010-01-30'
Declare cc cursor for select distinct empid from ta_timecard where schedindate between #FromDate and #ToDate
open cc
fetch next from cc into #empid
while (##fetch_status = 0)
begin
set #id = #id + 1
insert into ta_MonthlyAttendance (ID, EmpID) values (#id, #empid)
declare cc2 cursor for select distinct schedindate, TimeInR, TimeOutR from ta_timecard where empid = #empid and schedindate between #FromDate and #ToDate
open cc2
fetch next from cc2 into #schedindate, #TimeInR
while (##fetch_status = 0)
begin
set #indice = cast(datediff(day, #fromdate, #schedindate) as nvarchar(4))
set #TimeInR = (select TOP 1 ta_TimeCard.TimeInR from ta_TimeCard where (#schedindate between #FromDate and #ToDate) and EmpID=#empid)
set #schedindate = (select TOP 1 ta_TimeCard.SchedInDate from ta_TimeCard where (#schedindate between #FromDate and #ToDate) and empid=#empid)
set #ss = 'update ta_MonthlyAttendance set NOD ' + #indice + ' = + dbo.ta_dayofweek('+ char(39) + convert(nvarchar(50), #schedindate, 102) + char(39) +' ) , TimeInR ' + #indice + ' = + #TimeInR + where empid = ' + cast(#empid as nvarchar(20))
execute sp_executesql #ss
fetch next from cc2 into #schedindate, #TimeInR
end
close cc2
deallocate cc2
fetch next from cc into #empid
end
close cc
Deallocate cc
this code gives error in the line "fetch next from cc2 into #schedindate, #TimeInR"
where's my fault? I can't find it..
declare cc2 cursor for
select distinct schedindate, TimeInR, TimeOutR
from ta_timecard where empid = #empid
and schedindate between #FromDate and #ToDate
open cc2
fetch next from cc2 into #schedindate, #TimeInR
You are selecting schedindate, TimeInR, TimeOutR but the into statement has only #schedindate, #TimeInR
Try this one -
DECLARE
#empid INT
, #schedindate DATETIME
, #ss NVARCHAR(100)
, #indice NVARCHAR(2)
, #FromDate DATETIME
, #ToDate DATETIME
, #TimeInR DATETIME
, #TimeOutR DATETIME
SELECT
#FromDate = '20090114'
, #ToDate = '20100130'
DECLARE #temp TABLE
(
schedindate DATETIME
, TimeInR VARCHAR(10)
, TimeOutR VARCHAR(10)
, empid INT
)
INSERT INTO #temp (schedindate, TimeInR, TimeOutR, empid)
SELECT DISTINCT
schedindate
, TimeInR
, TimeOutR
, empid
FROM dbo.ta_timecard
WHERE schedindate BETWEEN #FromDate AND #ToDate
DECLARE #ids TABLE(id BIGINT IDENTITY(1,1), emp BIGINT)
INSERT INTO #ids (emp)
SELECT DISTINCT empid
FROM #temp
INSERT INTO dbo.ta_MonthlyAttendance(id, EmpID)
SELECT id, emp
FROM #ids
DECLARE cc CURSOR LOCAL FAST_FORWARD READ_ONLY FOR
SELECT DISTINCT empid
FROM #temp
OPEN cc
FETCH NEXT FROM cc INTO #empid
WHILE (##fetch_status = 0) BEGIN
SELECT
#indice = CAST(DATEDIFF(DAY, #fromdate, t.SchedInDate) AS NVARCHAR(4))
, #TimeInR = t.TimeInR
, #schedindate = t.SchedInDate
FROM #temp t
WHERE empid = #empid
SELECT #ss = 'update ta_MonthlyAttendance set NOD ' + #indice
+ ' = + dbo.ta_dayofweek(' + CHAR(39)
+ CONVERT(NVARCHAR(50), #schedindate, 102) + CHAR(39) + ' ) , TimeInR '
+ #indice + ' = ' + #TimeInR + ' where empid = ' + CAST(#empid AS NVARCHAR(20))
EXEC sys.sp_executesql #ss
FETCH NEXT FROM cc INTO #empid
END
CLOSE cc
DEALLOCATE cc