Error while declaring a new variable - sql

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]

Related

IF in Where with multiple Conditions

I am trying to write a query where I can have either of the 2 variables entered and the query needs to execute on the basis of which data was entered. For example
DECLARE #A NVARCHAR(15) = '' -- Input A here
-------------------OR---------------------
DECLARE #B NVARCHAR(15) = '' -- Input B here
SELECT
[DOC].[ety_ts] as [CreatedDate],
[DOC].[ord_int_id],
[DOC].[doc_int_id],
[pnt_cln_doc_int_id] as [ParentDoc],
CDTL_STATUS2.cod_dtl_ds as DocumentName,
CDTL_STATUS.[cod_dtl_ds] as [DocumentStatus],
.................................
..................................
.....................................
WHERE
IF ( #A IS NULL OR #A = '' )
BEGIN
DOC.asn_int_id = (Select asn_int_id from TPM(nolock) where rec_no=#B)
END
ELSE
BEGIN
DOC.ord_int_id IN
(
SELECT DOC.ord_int_id
FROM TAD_DOCUMENT WITH (NOLOCK)
WHERE DOC.ord_int_id IN
(
SELECT TPM.ord_int_id FROM TPM_VISIT TPM WITH (NOLOCK)
WHERE TPM300.vst_no = #A
)
END
It throws an error for the first IF Statement
Msg 156, Level 15, State 1, Line 59
Incorrect syntax near the keyword 'IF'.
Not sure what I am doing wrong. Can anyone please guide on how to fix this query.
Thanks in advance.
IF is a procedural statement, not a query clause. From the documentation:
An IF...ELSE construct can be used in batches, in stored procedures, and in ad hoc queries.
You just want regular AND/OR logic e.g.
WHERE (
NULLIF(#A,'') IS NULL
AND DOC.asn_int_id = (
SELECT asn_int_id
FROM TPM
WHERE rec_no = #B
)
)
OR (
NULLIF(#A,'') IS NOT NULL
AND DOC.ord_int_id IN (
SELECT DOC.ord_int_id
FROM TAD_DOCUMENT
WHERE DOC.ord_int_id IN (
SELECT TPM.ord_int_id
FROM TPM_VISIT TPM
WHERE TPM300.vst_no = #A
)
)
)
Note: Unless you are very sure you understand and accept the consequences of using NOLOCK I highly recommend not using it. Its not a "go faster for free" hint.

create table from if statement SQL

I have this code in my SQL, however the if statement seems to be not working at all. Every time I run the query below.. I always have an error that says...
Msg 2714, Level 16, State 1, Line 39
There is already an object named '##TEMP1' in the database.
QUERY BELOW...
IF (SELECT COUNT (*) FROM ##TEMP1 WHERE [ACTION] NOT LIKE 'ok' ) >=1
BEGIN
SELECT * INTO ##newtable FROM ##TEMP1 ORDER BY 1 ASC
Select ' ' = 'MESSAGE'
SELECT * FROM ##newtable
END
ELSE
BEGIN
Select [MESSAGE] = 'MESSAGE' INTO ##newtable
SELECT * FROM ##newtable
END
is there any way that the query creates a final table '##temp1' given that the condition is met? So it's either the first begin statement or the second one.
Thank you.

Error in selecting

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';

Use While loop to calculate values from Table?

I have a following Table Where I need to loop through the records and add values to a variable
Declare #Variable1 INT
SET #Variable1=0
Declare #totalval INT
SET #totalval=0
While (#Variable1<=20)
BEGIN
SET #totalval=#totalval+(Select Salary from EmpTable Where EmpID=9)
PRINT #totalval
SET #Variable1= Variable1+1
END
GO
I cant print the value...I am using SQL server 2005
Thank you all
You could use this instead:
;WITH a AS
(
SELECT ROW_NUMBER() OVER (ORDER BY (SELECT 0)) num
, *
FROM EmpTable
WHERE EmpID = 9
)
SELECT #totalval = SUM(Salary)
, #Variable1 = COUNT(*)
FROM a
WHERE num <= 20
This would be one of usual ways of doing such task and it's more efficient than looping. ROW_NUMBER() OVER (ORDER BY (SELECT 0)) gives ordinal numbers to records but doesn't change sort.
This is also working (for your requirement):
Fiddle demo here
declare #total int, #records int = 20
select top( #records) #total=isnull(#total,0) + salary
from EmpTable
where empid = 9
-- order by salary (you may need to order by something)
The problem is this line:
SET #Variable1= Variable1+1
that doesn't work, change it to this:
SET #Variable1= #Variable1+1
if you were to leave it you should be getting this error:
Msg 207, Level 16, State 1, Line 11
Invalid column name 'Variable1'.

SQL UDF Group By Parameter Issue

I'm having some issues with a group by clause in SQL. I have the following basic function:
CREATE FUNCTION dbo.fn_GetWinsYear (#Year int)
RETURNS int
AS
BEGIN
declare #W int
select #W = count(1)
from tblGames
where WinLossForfeit = 'W' and datepart(yyyy,Date) = #Year
return #W
END
I'm trying to run the following basic query:
select dbo.fn_GetWinsYear(datepart(yyyy,date))
from tblGames
group by datepart(yyyy,date)
However, I'm encountering the following error message: Column 'tblGames.Date' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.
Any ideas why this is occurring? FYI, I know I can remove the function and combine into one call but I'd like to keep the function in place if possible.
I think you should be calling your function like this.
select dbo.fn_GetWinsYear(datepart(yyyy,getdate()))
OR
select dbo.fn_GetWinsYear('2010')
Essentially you are just passing a year to your function and the function is returning the number of wins for that year.
If you don't know the year, your function could look something like this...
CREATE FUNCTION dbo.fn_GetWinsYear ()
RETURNS #tblResults TABLE
( W INT, Y INT )
AS
BEGIN
INSERT #tblResults
SELECT count(1), datepart(yyyy,[Date])
FROM tblGames
WHERE WinLossForfeit = 'W'
GROUP BY datepart(yyyy,[Date])
RETURN
END
SELECT * FROM dbo.fn_GetWinsYear()