Error in selecting - sql

I am trying to do a select like this -
SELECT COUNT(*)
FROM
(
DECLARE #Emp varchar(100)
SET #Emp = 'Rick'
SELECT *
FROM [Temporary].[dbo].[Employee_Test]
WHERE [Emp_Name] = #Emp
) AS EMPS
I know that I can fix this by putting the DECLARE statements before outer select. But, due to some crappy design, I would prefer to be able to use the inner query as is and then count the number of rows in it. How do I do that ?
The error I get is -
Msg 156, Level 15, State 1, Line 4
Incorrect syntax near the keyword 'DECLARE'.
Msg 102, Level 15, State 1, Line 9
Incorrect syntax near ')'

DECLARE #Emp varchar(100)
SET #Emp = 'Rick';
SELECT COUNT(*)
FROM [Temporary].[dbo].[Employee_Test]
WHERE [Emp_Name] = #Emp
You need to Declare The variable and SET its values before you pass it to the SELECT Statement. You cannot Declare a Variable Inside a Select Statement.

Should you put a semi-colon after the SET statement?
SET #EMP = 'Rick';

Related

select into a table using a variable as table name dynamic sql not working

I'm trying to execute the code below (I know a lot of people have already asked this question but none of them worked for me). since I have a loop I need to select into multiple new tables with the value of variable name as tables names.
I tried using dynamic sql for the tables name like this:
WHILE ( #Counter <= #len)
begin
DECLARE #name VARCHAR(10),#sql nvarchar(max)
SET #name= (select product from #ProductType where NewPK= #Counter)
set #sql='
select m=DATEPART(month,t2.initial_date),y=DATEPART(year,t2.initial_date) ,t1.user_orders,t1.account_id
into '+#name+'
from (select dbo.sales_info.account_id, count(*) as user_orders
from dbo.sales_info
where dbo.sales_info.product= #name
group by dbo.sales_info.account_id) t1
left join
(select dbo.sales_info.account_id, initial_date= min( dbo.sales_info.start_date)
from dbo.sales_info group by dbo.sales_info.start_date,dbo.sales_info.account_id )t2
on t1.account_id=t2.account_id
order by m,y'
exec (#sql)
SET #Counter = #Counter + 1
end
but I keep getting this error :
Must declare the scalar variable "#name".
Msg 102, Level 15, State 1, Line 10
Incorrect syntax near 't2'.
Msg 137, Level 15, State 2, Line 6
Must declare the scalar variable "#name".
Msg 102, Level 15, State 1, Line 10
Incorrect syntax near 't2'.
The problem is this line of code:
where dbo.sales_info.product = #name
You can use parameters when you execute the code:
exec sp_executesql #sql,
N'#name varchar(10),
#name=#name;

Error while declaring a new variable

I need to create a new variable (average of AGE) that I would like to get from another table named:source_table.
I wrote the following lines but got an error:
DECLARE #mean_AGE decimal;
set #mean_AGE = select AVG( AGE ) from source_table;
Error details:
Msg 156, Level 15, State 1, Line 33
Incorrect syntax near the keyword 'select'.
How can I solve this issue?
An update:
I used this code based on the answers below but still an error.
DECLARE #mean_AGE decimal;
select #mean_AGE = AVG(AGE) from source_table;
--DELETE temp_table
SELECT TOP 1000
[AGE]=iif(AGE='NA',#mean_AGE,AGE)
INTO temp_table
FROM [source_table]
But got this error:
Must declare the scalar variable "#mean_AGE".
Try this instead, use a select. set #mean_AGE = (select AVG( AGE ) from source_table)
Change the query to:
select #mean_AGE = AVG(AGE) from source_table;
Updates
Remove those semi-colons
DECLARE #mean_AGE decimal
select #mean_AGE = AVG(AGE) from source_table
; denotes end of batch script so a statement after that is effectively new batch script.
Secondly,
This one will not work because the data type in iif true and false condition must match.
SELECT TOP 1000
[AGE]=iif(AGE='NA',#mean_AGE,AGE)
INTO temp_table
FROM [source_table]
Change to:
SELECT TOP 1000
[AGE]=iif(AGE=0,#mean_AGE,AGE)
INTO temp_table
FROM [source_table]

Using Cross Joins individually

I am trying this statement:
Declare #Param1 int = 0
SELECT #Param1,T.N
CROSS JOIN (VALUES(0),(1),(2)) as T(N)
Returns this error:
Msg 156, Level 15, State 1
Incorrect syntax near the keyword 'CROSS'.
It seems I can only use this Cross Join when I use FROM first, but not by itself?
I guess when you do it like this it works:
SELECT #Param1,T.N
FROM (VALUES(0),(1),(2)) as T(N)
Yes, you cannot do a join outside of a from statement. Use a table var for param and join it?
Declare #Param1 table(param1 int);
insert into #param1 values(0)
SELECT *
from #Param1
CROSS JOIN (VALUES(0),(1),(2)) as T(N);

Syntax error using multiple CTEs

I have a rather complicated CTE that I'm attempting to incorporate into a stored procedure. It works when just operating straight from SQL Server Management Studio. When I try to create my stored procedure, I get an error:
Msg 102, Level 15, State 1, Procedure spMyCrazyProc, Line 56
Incorrect syntax near ','.
What have I syntactically done incorrectly when trying to incorporate my CTE into a stored procedure?
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[spMyCrazyProc]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[spMyCrazyProc]
GO
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE dbo.spMyCrazyProc
#CompanyId Int,
#EmployeeIds varchar(MAX)
AS
;with SelectedEmployees as (
select * from vwEmployee e
where e.CompanyId = #CompanyId
and (#EmployeeIds is null or #EmployeeIds='' or exists(select ce.SelectedEmployeeId from #myTmpTable ce where ce.SelectedEmployeeId=e.EmployeeId)
), MyStuffA as (
select * from SelectedEmployees
)
select * from MyStuffA
GO
Using sensible coding conventions and thinking about readability (indenting, carriage returns) would have yielded this simple error much more clearly. Your code with 500 character-wide lines removed:
;with SelectedEmployees as
(
select * from vwEmployee e
where e.CompanyId = #CompanyId
and
(
#EmployeeIds is null or #EmployeeIds='' or exists
(
select ce.SelectedEmployeeId from #myTmpTable ce
where ce.SelectedEmployeeId=e.EmployeeId
)
----^----- oops! Missing closing paren here.
), MyStuffA as
(
select * from SelectedEmployees
)
select * from MyStuffA

use a "temporary table" and "while loop" together in sql

I want to create a table and after that use the table information in a while loop. I had been used 'with' to create the table but my code has error. The code comes below:
declare #i integer
set #i=0;
with cte as
(SELECT ROW_NUMBER()OVER(ORDER BY ItemID) as RowNumber,*,DATEDIFF(day,GETDATE(),AdDateTo)as DaysToExpire
FROM KenticoCMS1.dbo.AD_Advertise inner join KenticoCMS1.dbo.CMS_User
ON KenticoCMS1.dbo.AD_Advertise.ItemCreatedBy = KenticoCMS1.dbo.CMS_User.UserID
WHERE DATEDIFF(day,GETDATE(),AdDateTo) in (SELECT RemainDays FROM KenticoCMS1.dbo.AD_SendEmailForExpire)
AND AdShow=1)
--SELECT * FROM cte
while ( #i<=(select max(RowNumber) from cte))
BEGIN
#i=#i+1;
EXEC msdb.dbo.sp_send_dbmail #profile_name='ExpireAdvertiseEmail',
#recipients= select Email FROM cte where RowNumber=#i , --'mj.yazdani1988#gmail.com',
#subject='Test message',
#body='This is the body of the test message.Congrates Database Mail Received By you Successfully.'
END
GO
and my error:
Msg 156, Level 15, State 1, Line 13
Incorrect syntax near the keyword 'while'.
Msg 156, Level 15, State 1, Line 16
Incorrect syntax near the keyword 'select'.
Msg 102, Level 15, State 1, Line 16
Incorrect syntax near ','.
You cannot use CTE as temporary table. You could create table (or declare table variable), put your data there and do your work:
create table #temp (RowNumber int, Email nvarchar(max)
But so far looks like your code could be changed like this:
declare #Email nvarchar(max)
declare cur cursor local fast_forward for
select
u.Email
from KenticoCMS1.dbo.AD_Advertise as a
inner join KenticoCMS1.dbo.CMS_User as u on u.UserID = a.ItemCreatedBy
where
a.AdShow = 1 and
datediff(day, getdate(), a.AdDateTo) in
(
select t.RemainDays
from KenticoCMS1.dbo.AD_SendEmailForExpire as t
)
open cur
while 1 = 1
begin
fetch cur into #Email
if ##fetch_status <> 0 break
exec msdb.dbo.sp_send_dbmail
#profile_name = 'ExpireAdvertiseEmail',
#recipients = #Email,
#subject = 'Test message',
#body = 'This is the body of the test message.Congrates Database Mail Received By you Successfully.'
end
close cur
deallocate cur
Note table aliases, removing redundant brackets. I think it'll also helps to remove datediff, but have to see your data before.
try this: put this part
while ( #i<=(select max(RowNumber) from cte))
BEGIN
#i=#i+1;
EXEC msdb.dbo.sp_send_dbmail #profile_name='ExpireAdvertiseEmail',
#recipients= (
before
with cte as
and a
)
after
...where RowNumber=#i
for my understanding the cte definition must be followed directly by select (and it can be used in only that one select that follows)
hope it helps...
EDIT: commas obviously part of parameterlist for function