Error in using IF EXISTS in SQL Server 2005 - sql-server-2005

This is my query, but I am getting an error. Please help how to do it
declare #spid varchar(20)
if exists ((select #spid = Sponsor_Id from UserTransaction) where User_id= 'RL0814')
insert into UserTransaction(Sponsor_Id, User_Id)
values (#spid,'RL4108')
The error is:
Incorrect syntax near '='

Try this instead:
DECLARE #spid VARCHAR(20)
SET #spid = NULL
SELECT #spid = Sponsor_Id
FROM dbo.UserTransaction
WHERE User_id = 'RL0814'
IF #spid IS NOT NULL
INSERT INTO dbo.UserTransaction(Sponsor_Id, User_Id)
VALUES (#spid, 'RL4108')

Related

Getting Error Column name or number of supplied values does not match table definition

when I am executing this stored procedure, I get an error:
Msg 213, Level 16, State 7, Line 1
Column name or number of supplied values does not match table definition.
Code:
alter procedure AutoUpdate_EmpSal
as
begin
DECLARE #cmd AS NVARCHAR(max)
CREATE TABLE #result
(
SalaryId int,
EmpId INT,
TakenSalary float,
AvailSalary float
)
declare #salaryId int
declare #empId int
declare #takenSalary float
declare #availSalary float
SET #cmd ='select * from Employee_SalaryDetails where SalaryId in( SELECT max(SalaryId) FROM Employee_SalaryDetails group by EmpId )'
Insert into #result
EXEC(#cmd)
declare result_cursor cursor for
select SalaryId,EmpId,TakenSalary,AvailSalary
from #result
OPEN result_cursor
FETCH NEXT FROM result_cursor INTO #salaryId,#empId,#takenSalary,#availSalary
WHILE ##FETCH_STATUS = 0
BEGIN
update Employee_SalaryDetails
set Employee_SalaryDetails.AvailSalary=(#availSalary+Employee.Salary)
from Employee_SalaryDetails,Employee
where Employee_SalaryDetails.SalaryId=#salaryId
and Employee_SalaryDetails.EmpId=Employee.EmpId
FETCH NEXT FROM result_cursor INTO #salaryId,#empId,#takenSalary,#availSalary
end
select * from #result
end
Remove the '*' from your cmd query and select those columns which have in #result table as it is..
Perhaps, you can select detail columns to insert. You can change this code:
select * from Employee_SalaryDetails
where SalaryId in( SELECT max(SalaryId) FROM Employee_SalaryDetails group by EmpId)
to code:
select SalaryId, EmpId, TakenSalary, AvailSalary FROM Employee_SalaryDetails
where SalaryId in( SELECT max(SalaryId) FROM Employee_SalaryDetails group by EmpId)

How to use SQL Variables inside a query ( SQL Server )?

I have written the following SQL Stored Procedure, and it keeps giving me the error at
#pid = SELECT MAX(... The whole procedure is:
Alter PROCEDURE insert_partyco
#pname varchar(200)
AS
BEGIN
DECLARE #pid varchar(200);
#pid = SELECT MAX(party_id)+1 FROM PARTY;
INSERT INTO party(party_id, name) VALUES(#pid, #pname)
SELECT SCOPE_IDENTITY() as PARTY_ID
END
GO
Can anyone please tell me what I'm doing wrong here?
Alter PROCEDURE insert_partyco
#pname varchar(200)
AS
BEGIN
DECLARE #pid varchar(200);
SELECT #pid = MAX(party_id)+1 FROM PARTY;
INSERT INTO party(party_id, name) VALUES(#pid, #pname)
SELECT SCOPE_IDENTITY() as PARTY_ID
END
This has an advantage over SET with SELECT in that you can select expressions in multiple variables in one statement:
SELECT #var1 = exp1, #var2 = expr2 ... etc
declare #total int
select #total = count(*) from news;
select * from news where newsid = #total+2
//**news** table name and **newsid** column name
You need to use SET.
Alter PROCEDURE insert_partyco
#pname varchar(200)
AS
BEGIN
DECLARE #pid varchar(200);
SET #pid = (SELECT MAX(party_id)+1 FROM PARTY);
INSERT INTO party(party_id, name) VALUES(#pid, #pname)
SELECT SCOPE_IDENTITY() as PARTY_ID
END
GO
Alternatively, in your case you could make party_id an autoincremented value, so you wouldn't need to query the table.

SQL Looping temp table and reading data

I have following script to create temp data
DECLARE #Name NVARCHAR(100), #Marks INT
DECLARE #MYTABLE TABLE
(
[Name][nvarchar](100) NULL,
[Marks][INT] NULL
)
INSERT INTO #MYTABLE ([Name],[Marks]) VALUES ('Mark',50);
INSERT INTO #MYTABLE ([Name],[Marks]) VALUES ('Steve',50);
INSERT INTO #MYTABLE ([Name],[Marks]) VALUES ('Don',50);
Now I want loop it, as shown in below script
SELECT #MaxPK = MAX(PK) from #MYTABLE
WHILE #PK <= #MaxPK
BEGIN
SET #Name = SELECT Name from #MYTABLE
SET #Marks = SELECT Marks from #MYTABLE
print #Name
print #Marks
SET #PK = #PK + 1
END
But I get error near SELECT statement.
"Incorrect syntax near the keyword SELECT"!
The two rows where you set the variables can be put together like this. That way you will only scan the table once.
SELECT #Name = Name, #Marks = Marks FROM #MYTABLE
Just know that the row chosen to be put in your variables is completely arbitary (and will probably be the same row every time) unless you add a whereclause.
Please try below while loop:
WHILE #PK <= #MaxPK
BEGIN
SELECT #Name = Name, #Marks = Marks from #MYTABLE
print #Name
print #Marks
END
Note: I guess, a where condition is required in select statement in order to print all data.

call sql function in stored procedure with different userId each time

I have a sql function and using sql server 2005.
dbo.util (#dailyDate,#userId)
Now I want to call this function for each #userId for a particular Date.So I am writing a Stored Procedure.
Create PROCEDURE [dbo].[DailyAttendenceTemp]
#dailyDate nvarchar(10)
WITH EXEC AS CALLER
AS
Select * FROM dbo.util (#dailyDate,#userId) //I think error is here.
WHERE #userId in (SELECT UserId From TTransactionLog1)
GO
but when I execute the procedure it give the error that-
SQL Server Database Error: Must declare the scalar variable "#userId".
So please tell me how to correct the procedure so that I give only date as a parameter and it run for the same function for each #userId.
I got the answer,,now I am using While loop and it solve my problem.......
DECLARE #i int
DECLARE #userid nvarchar(10)
DECLARE #numrows int
DECLARE #tempUserId_table TABLE (
idx smallint Primary Key IDENTITY(1,1)
, userid nvarchar(10)
)
INSERT #tempUserId_table
SELECT distinct UserID FROM TUser
-- enumerate the table
SET #i = 1
SET #numrows = (SELECT COUNT(*) FROM #tempUserId_table)
IF #numrows > 0
WHILE (#i <= (SELECT MAX(idx) FROM #tempUserId_table))
BEGIN
-- get the next userId primary key
SET #userid = (SELECT userid FROM #tempUserId_table WHERE idx = #i)
Select * FROM dbo.util (#dailyDate,#userid)
-- increment counter for next userId
SET #i = #i + 1
END

Trigger to update table according to user rank

I'm a stranger to SQL Server Triggers.
I ended up having a problem like this. Please have a look.
I have two tables 'users' & 'test'
CREATE TABLE users(
email VARCHAR(250),
rank FLOAT
);
CREATE TABLE test(
score INT,
total INT
);
I need to create a trigger to;
2.1 Update users rank by the value of avg ( avg = test.score / test.total)
2.2 Here's What I tried so far:
CREATE TRIGGER auto_rank ON dbo.test FOR INSERT
BEGIN
DECLARE #sc INT
DECLARE #tot INT
DECLARE #avg FLOAT
#tot = SELECT inserted.total FROM dbo.test
#sc = SELECT inserted.score FROM dbo.test
SET #avg=#sc/#tot
UPDATE dbo.users SET rank=#avg WHERE email=inserted.email
END
You missing the email in test from your table design, but it should have such column per your code:
UPDATE dbo.users SET rank=#avg WHERE email=inserted.email
Then you need a view instead of trigger in this case:
Create view user as (select email, score/total as rank from test group by email);
Hope this help.
Try this :
CREATE TRIGGER auto_rank ON dbo.test FOR INSERT
BEGIN
UPDATE a SET a.rank=b.rn
from
users a
inner join
(select email,inserted.score/inserted.total rn from inserted)b
on a.email=b.email
END
I have not tested this, but this should work fine.
You need to modify your tables so that the test table contains the email column:
CREATE TABLE test(score INT,
total INT,
email varchar(250)
);
Then you can create the trgiger like this:
CREATE TRIGGER [dbo].[auto_rank] ON [dbo].[test]
FOR INSERT
AS
BEGIN
DECLARE MyCursor CURSOR FOR
SELECT score, total, email FROM Inserted
DECLARE #sc INT
DECLARE #tot INT
DECLARE #email VARCHAR(30)
DECLARE #avg FLOAT
DECLARE #MSG VARCHAR(50)
OPEN MyCursor;
FETCH NEXT FROM MyCursor INTO #sc, #tot, #email
WHILE ##FETCH_STATUS = 0
BEGIN
SELECT #avg=#sc/#tot
UPDATE users SET rank=#avg WHERE users.email=#email
SELECT #MSG = 'email Updated ' + #email + '. New Rank is ' + Str(#avg, 25, 5);
PRINT #MSG
FETCH NEXT FROM MyCursor
END;
CLOSE MyCursor;
DEALLOCATE MyCursor;
END
Sorry for being so late to continue this thread but, I'm happy to say that I found the answer. it's because of you all.
So, here's what i did;
first;
CREATE TABLE users(
email VARCHAR(250),
rank FLOAT,
constraint pk_users PRIMARY KEY(email)
);
CREATE TABLE test(
email VARCHAR(250),
score INT,
total INT,
constraint pk_test PRIMARY KEY(email),
constraint fk_from_users FOREIGN KEY(email) references users(email)
);
create trigger trig_ex02 on dbo.test
after insert
as
begin
declare #score FLOAT
declare #total FLOAT
declare #average FLOAT
declare #msg varchar(100)
declare #email varchar(250)
set #email = (select email from inserted)
set #score = (select score from inserted)
set #total = (select total from inserted)
set #average =(#score/#total)
select #msg = 'SCORE IS'+ str(#score)+'TOTAL IS'+str(#total)+' AVERAGE IS ' +str(#average,25,5)+' END '
print #msg
UPDATE users SET rank=#average WHERE users.email=#email
end;