add custom messages in a stored procedure - sql-server

i want to add some messages in my stored procedure according to if else condition how can i do that. the issue is i have three tables team , account and user. i want to delete the teamA in team table only on the condition if there is not any account and user is related to that team. i have the stored procedure which is working fine but i want to check the condition and want to add some custom messages using if else . please help here is my code.
Create PROCEDURE sp_DeleteTeam
#pTeamId int
AS
BEGIN
SET NOCOUNT ON;
update t
set t.Deleted =1
from Team t
where t.TeamId = #pTeamId
And Not Exists (Select 1 from [User] where TeamId = #pTeamId)
And Not Exists (Select 1 from Account where TeamId = #pTeamId)
END

Don't use the prefix sp_ for user stored procedures as that is reserved for system procs.
Below is an example that returns the message using RAISERROR. A severity of 11 or higher as in this example will raise an exception in the application. Severity of 10 or lower will generate an informational message.
CREATE PROCEDURE usp_DeleteTeam #pTeamId int
AS
BEGIN
SET NOCOUNT ON;
DECLARE #Message varchar(2047);
UPDATE t
SET t.Deleted = 1
FROM Team t
WHERE t.TeamId = #pTeamId
AND NOT EXISTS ( SELECT 1
FROM [User]
WHERE TeamId = #pTeamId )
AND NOT EXISTS ( SELECT 1
FROM Account
WHERE TeamId = #pTeamId );
IF ##ROWCOUNT = 0
BEGIN
IF NOT EXISTS ( SELECT *
FROM Team
WHERE TeamId = #pTeamId )
BEGIN
SET #Message = 'does not exist in Team table';
END;
IF EXISTS ( SELECT *
FROM [User]
WHERE TeamId = #pTeamId )
BEGIN
SET #Message = COALESCE(#Message + ', ', '')
+ 'already exists in User table';
END;
IF EXISTS ( SELECT *
FROM Account
WHERE TeamId = #pTeamId )
BEGIN
SET #Message = COALESCE(#Message + ', ', '')
+ 'already exists in Account table';
END;
SET #Message = 'Team %d: ' + #Message
RAISERROR(#Message, 11, 0, #pTeamId);
END;
END;

Use the below SP to use print or select message.
Create PROCEDURE sp_DeleteTeam
#pTeamId int
AS
BEGIN
SET NOCOUNT ON;
IF ((NOT EXISTS (SELECT TOP 1 FROM [User] WHERE TeamId = #pTeamId)) AND (Not EXISTS (SELECT TOP 1 FROM Account WHERE TeamId = #pTeamId)))
BEGIN
UPDATE T
SET T.Deleted = 1
FROM Team t
WHERE T.TeamId = #pTeamId
SELECT 'Not exist - Table updated' AS Message
--PRINT 'Not exist - Table updated'
END
ELSE
BEGIN
SELECT 'Already exist - Table not updated.' AS Message
--PRINT 'Already exist - Table not updated.'
END
END

As far as I understood you just want to see if it executed sucessfully. If the stored Procedure is being called In some Applciation, At the end, Give a select statement as
SELECT 'Your message' AS Message
Then in application store the result in Dataset and retrieve your message,
If you are not using it in any application, then simply use
print 'your message'
OR may be try to be more specific and elaborate you problem a bit clearly.

Related

insert data into sql table and get recent inserted iD and insert data in same table from different table

Here is the situation that I have to insert profile photos in the SQL table. But here are 2 scenarios the condition
if user is inserting photo and data from front end. Its working perfectly fine.
if user is skip the photo and just inserting his biography then in that case the default image should be inserted by default. I tried to do in front end Just adding dummy image in if else condition, but in DMZ server for some reason this is creating problem, on local server its working good.
Here is the Query...
ALTER PROCEDURE [dbo].[SavePhysicianBiodata]
-- Add the parameters for the stored procedure here
#ID int,
#Physician_Bio nvarchar(MAX),
#Physician_Mnemonic nvarchar(MAX),
#Physician_Image image,
#Physician_ImageType nvarchar(MAX),
#Physician_ImageFileName nvarchar(MAX)
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
if( #ID is null OR #ID='')
begin
--if not image then deafult image will be applied
if((#Physician_ImageType is null or #Physician_ImageType='') and
(#Physician_ImageFileName is null or #Physician_ImageFileName='') )
begin
insert into Physician_Biodata(Physician_Bio, Physician_Mnemonic)
values(#Physician_Bio, #Physician_Mnemonic)
set #ID = SCOPE_IDENTITY()
update [dbo].[Physician_Biodata]
set Physician_Image=#Physician_Image,
Physician_ImageType=#Physician_ImageType,
Physician_ImageFileName=#Physician_ImageFileName
where ID=#ID
end
else
begin
-- Insert statements for procedure here when user adds photo as well
insert into Physician_Biodata(Physician_Bio, Physician_Mnemonic,
Physician_Image, Physician_ImageType, Physician_ImageFileName)
values(#Physician_Bio, #Physician_Mnemonic,
#Physician_Image,#Physician_ImageType,#Physician_ImageFileName)
end
end
else
begin
update [dbo].[Physician_Biodata]
set Physician_Bio=#Physician_Bio,
Physician_Mnemonic=#Physician_Mnemonic,
Physician_Image=#Physician_Image,
Physician_ImageType=#Physician_ImageType,
Physician_ImageFileName=#Physician_ImageFileName
where ID=#ID
end
END
In this query I also tried insert query which is given below
insert into Physician_Biodata(ID, Physician_Image, Physician_ImageType, Physician_ImageFileName)
select #ID, dd.Physician_Image,dd.Physician_ImageType,dd.Physician_ImageFileName from DefaultImage as dd
join Physician_Biodata
on Physician_Biodata.Physician_ImageFileName = dd.Physician_ImageFileName
where Physician_Biodata.ID = #ID
but getting error during execute procedure
Msg 544, Level 16, State 1, Procedure dbo.SavePhysicianBiodata, Line 35 [Batch Start Line 2]
Cannot insert explicit value for identity column in table 'Physician_Biodata' when IDENTITY_INSERT is set to OFF.
If somebody can help me it would be great.. Thanks in advance.
Yes I have already changed the first insert statement (removed ID) and
updated the 2nd query
set #ID = IDENT_CURRENT('Physician_Biodata')
update Physician_Biodata
set Physician_Biodata.Physician_Image= DefaultImage.Physician_Image, Physician_Biodata.Physician_ImageType= DefaultImage.Physician_ImageType, Physician_Biodata.Physician_ImageFileName=DefaultImage.Physician_ImageFileName from Physician_Biodata, DefaultImage where Physician_Biodata.ID=#ID
and it worked
It appears that Physician_Biodata's ID column is an IDENTITY, hence the exception you have.
Changing this...
INSERT INTO Physician_Biodata (
ID, Physician_Image, Physician_ImageType, Physician_ImageFileName
)
SELECT
#ID,
dd.Physician_Image,
dd.Physician_ImageType,
dd.Physician_ImageFileName
FROM DefaultImage AS dd
JOIN Physician_Biodata
ON Physician_Biodata.Physician_ImageFileName = dd.Physician_ImageFileName
WHERE
Physician_Biodata.ID = #ID;
To this...
INSERT INTO Physician_Biodata (
Physician_Image, Physician_ImageType, Physician_ImageFileName
)
SELECT
dd.Physician_Image,
dd.Physician_ImageType,
dd.Physician_ImageFileName
FROM DefaultImage AS dd
JOIN Physician_Biodata
ON Physician_Biodata.Physician_ImageFileName = dd.Physician_ImageFileName
WHERE
Physician_Biodata.ID = #ID;
Will make your "explicit value" exception go away as in your INSERT you are attempting to insert #ID into ID which is an identity column. You also use ID = #ID in your WHERE clause, which makes inserting #ID pointless as this would be a chicken-and-egg issue.
On another note, if #Physician_ImageType and #Physician_ImageFileName are both NULL going in, they'll still be NULL on your UPDATE given your existing SP's logic.
I've taken a little liberty to tidy/simplify your T-SQL and added a note about what I've questioned.
ALTER PROCEDURE [dbo].[SavePhysicianBiodata] (
#ID int,
#Physician_Bio nvarchar(MAX),
#Physician_Mnemonic nvarchar(MAX),
#Physician_Image image,
#Physician_ImageType nvarchar(MAX),
#Physician_ImageFileName nvarchar(MAX)
)
AS
BEGIN
SET NOCOUNT ON;
IF ISNULL( #ID, '' ) = ''
BEGIN
--if not image then deafult image will be applied
IF ISNULL( #Physician_ImageType, '' ) = '' AND ISNULL( #Physician_ImageFileName, '' ) = ''
BEGIN
INSERT INTO Physician_Biodata ( Physician_Bio, Physician_Mnemonic )
VALUES ( #Physician_Bio, #Physician_Mnemonic ) ;
SET #ID = SCOPE_IDENTITY();
/*
Where are you setting the values for #Physician_Image, #Physician_ImageType, and #Physician_ImageFileName? These are still NULL?
*/
UPDATE [dbo].[Physician_Biodata]
SET
Physician_Image = #Physician_Image,
Physician_ImageType = #Physician_ImageType,
Physician_ImageFileName = #Physician_ImageFileName
WHERE
ID = #ID;
END
ELSE BEGIN
-- Insert statements for procedure here when user adds photo as well
INSERT INTO Physician_Biodata (
Physician_Bio, Physician_Mnemonic, Physician_Image, Physician_ImageType, Physician_ImageFileName
)
VALUES (
#Physician_Bio, #Physician_Mnemonic, #Physician_Image, #Physician_ImageType, #Physician_ImageFileName
);
END
END
ELSE BEGIN
UPDATE [dbo].[Physician_Biodata]
SET
Physician_Bio = #Physician_Bio,
Physician_Mnemonic = #Physician_Mnemonic,
Physician_Image = #Physician_Image,
Physician_ImageType = #Physician_ImageType,
Physician_ImageFileName = #Physician_ImageFileName
WHERE
ID = #ID;
END
END

MSSQL2016 UPDATE trigger to INSERT record in other table based on SUM of bit column

I'm attempting to automate our order status update system. Here is the flow we have in place:
orders come in to our system as one order (via FTP file), and get split into 2 or more orders (inserted into SplitOrdersHeader_tb)
resulting multiple orders are sent from the SplitOrders tables (header and detail) to ERP system
ERP system produces order confirmations for each order (inserted into OrderConfirmationHeader_tb, and detail table)
need to update original single order status after all split order confirmations have been received
Here are the tables involved:
CREATE TABLE SplitOrdersHeader_tb(
OriginalCustomerPONumber varchar(20),
NewCustomerPONumber varchar(20),
Company varchar(2),
CustomerNumber varchar(10),
OrderProcessed bit DEFAULT 0,
OrderMoved bit DEFAULT 0,
OrderConfirmationReceived bit DEFAULT 0
)
CREATE TABLE OrderConfirmationHeader_tb(
MasterOrderNumber varchar(20),
CustomerPONumber varchar(20),
Company varchar(2),
CustomerNumber varchar(10)
)
CREATE TABLE UpdateOtherSystem_tb(
OriginalCustomerPONumber varchar(20)
)
I have a trigger on the OrderConfirmationHeader_tb that updates the status of each split order, once the order confirmations have been loaded:
CREATE TRIGGER dbo.INSERT_Update_SplitOrderConfirmations_tg
ON dbo.OrderConfirmationHeader_tb
AFTER INSERT
AS
SET NOCOUNT ON
BEGIN
UPDATE SOH
SET SOH.OrderConfirmationReceived = 1,
SOH.MasterOrderNumber = LTRIM(RTRIM(I.MasterOrderNumber))
FROM OrderSplitting.SplitOrdersHeader_tb SOH
INNER JOIN inserted I ON SOH.CustomerNumber = I.Customer
AND SOH.NewCustomerPONumber = I.Reference
AND SOH.Company = I.Company
AND SOH.OrderProcessed = 1
AND SOH.OrderMoved = 1
END
What I'm wanting to do is create an UPDATE trigger on the SplitOrdersHeader_tb that will:
- count the number of split orders from the original CustomerPONumber
- sum the number of OrderConfirmationReceived values
- if COUNT = SUM then insert a new record into UpdateOtherSystem_tb, provided the MasterOrderNumber does not already exist in the UpdateOtherSystem_tb
I have this, but it feels way too clunky:
CREATE TRIGGER OrderSplitting.UPDATE_Update_WCO_Status_tg
ON OrderSplitting.SplitOrdersHeader_tb
AFTER UPDATE AS
SET NOCOUNT ON
BEGIN
DECLARE #NEW_CUSTOMER_PO_NUMBER varchar(255),
#ORIGINAL_CUSTOMER_PO_NUMBER varchar(255),
#COUNT_OF_ORDER_HEADERS int,
#TOTAL_CONFIRMED_ORDERS int
SELECT #NEW_CUSTOMER_PO_NUMBER = NewCustomerPONumber
FROM inserted
SELECT #ORIGINAL_CUSTOMER_PO_NUMBER = OriginalCustomerPONumber,
#COUNT_OF_ORDER_HEADERS = COUNT(*),
#TOTAL_CONFIRMED_ORDERS = SUM(CAST(OrderConfirmationReceived as int))
FROM OrderSplitting.SplitOrdersHeader_tb
WHERE OriginalCustomerPONumber IN (SELECT OriginalCustomerPONumber
FROM OrderSplitting.SplitOrdersHeader_tb
WHERE NewCustomerPONumber = #NEW_CUSTOMER_PO_NUMBER)
GROUP BY OriginalCustomerPONumber
IF #COUNT_OF_ORDER_HEADERS = #TOTAL_CONFIRMED_ORDERS
BEGIN
BEGIN TRY
INSERT INTO OrderSplitting.UpdateOtherSystem_tb(OriginalCustomerPONumber)
VALUES(#ORIGINAL_CUSTOMER_PO_NUMBER)
END TRY
BEGIN CATCH
DECLARE #ERROR_MESSAGE varchar(MAX)
SET #ERROR_MESSAGE = ERROR_MESSAGE()
EXEC msdb..sp_send_dbmail
#recipients = <app_support>,
#subject = 'Update Trigger Error',
#body = #ERROR_MESSAGE
END CATCH
END
END
I think I have something, but would like some additional feedback, please:
CREATE TRIGGER OrderSplitting.UPDATE_Update_WCO_Status_tg
ON OrderSplitting.SplitOrdersHeader_tb
AFTER UPDATE AS
SET NOCOUNT ON
BEGIN TRY
INSERT INTO OrderSplitting.UpdateOtherSystem_tb(OriginalCustomerPONumber)
SELECT SOH.OriginalCustomerPONumber
FROM OrderSplitting.SplitOrdersHeader_tb SOH
INNER JOIN inserted I ON SOH.OriginalCustomerPONumber = I.OriginalCustomerPONumber
LEFT OUTER JOIN OrderSplitting.UpdateOtherSystem_tb UOS ON SOH.OriginalCustomerPONumber = UOS.OriginalCustomerPONumber
WHERE UOS.OriginalCustomerPONumber IS NULL
GROUP BY SOH.OriginalCustomerPONumber
HAVING COUNT(SOH.OriginalCustomerPONumber) = SUM(CAST(SOH.OrderConfirmationReceived as int))
END TRY
BEGIN CATCH
DECLARE #ERROR_MESSAGE varchar(MAX)
SET #ERROR_MESSAGE = ERROR_MESSAGE()
EXEC msdb..sp_send_dbmail
#recipients = <app_support>,
#subject = 'Update Trigger Error',
#body = #ERROR_MESSAGE
END CATCH

IF NOT EXIST insert ELSE IF update ELSE IF EXISTS and is not Numeric DELETE From WHERE

I want to modify the Stored Procedure below.
#UserID INT
#Unlock VARCHAR(4)
AS
SET NOCOUNT ON
IF NOT EXISTS (SELECT * FROM dbo.tblUnlockCode WHERE iUserID = #UserID)
BEGIN
IF ISNUMERIC(#Unlock) = 1
BEGIN
INSERT dbo.tblUnlockCode (iUserID, sUnlockCode) VALUES (#UserID, #Unlock)
END
I would actually like to add to it, to where if the iUserID exists Update the #Unlock to the new Pin, and if the iUserID exists on the table but the #Unlock gets erased on the textfield(in access) it gets removed from the Table. I only want to store the iUserIDs that 4 digit pins. How could I do that?
P.S. on access I am checking if the pin is 4 digits.
Try this (I also recommend adding error handling if you have none):
#UserID INT
#Unlock VARCHAR(4)
AS
SET NOCOUNT ON
IF NOT EXISTS (SELECT * FROM dbo.tblUnlockCode WHERE iUserID = #UserID)
BEGIN
IF ISNUMERIC(#Unlock) = 1
BEGIN
INSERT dbo.tblUnlockCode (iUserID, sUnlockCode) VALUES (#UserID, #Unlock)
END
END
ELSE
BEGIN
IF ISNUMERIC(#Unlock) = 1
BEGIN
UPDATE dbo.tblUnlockCode set sUnlockCode=#Unlock WHERE iUserID= #UserID
END
ELSE --Assuming you want to clear the record if unlock code is empty
BEGIN
DELETE dbo.tblUnlockCode WHERE iUserID= #UserID
END
END

Finding a user account in a SQL Server database?

Is there a way to find a particular user account in a database on a SQL Server?
Typically you would add an account to the SQL Server, at which point you can also map the user to multiple databases on that server. As long as no one does anything bad, you can return to the account properties on the server as see the databases the account was mapped to.
However, this linkage can be easily broken, where an account exists in a database, but it does not show up as mapped to that database at the server level. Also, you cannot create an account on the server if it already exists in one of the databases, this is the situation I'm in.
There are 100's of databases and I need to find the one that this users account is in. As far as I know sys.database_principals us unique to each database. Is it possible to do a cross database search for an account and return the database(s) that it exists in?
Here are some helper queries.
declare #returnValue int
EXEC #returnValue = sp_change_users_login 'Update_One', 'SXAUtil', 'SXAUtil'
print '/#returnValue/'
print #returnValue
print ''
select * from master..syslogins where name='MyUser001'
select * from [MyDatabase001]..sysusers where name='MyUser001'
select 1 as 'Match??' , mastSysLogin.sid as mastSysLogin_Sid, localSysLogin.sid as localSysLogin_Sid, mastSysLogin.name as mastSysLogin_Name , localSysLogin.name as localSysLogin_Name from master..syslogins mastSysLogin join [MyDatabase001]..sysusers localSysLogin on mastSysLogin.sid = localSysLogin.sid
where mastSysLogin.name='MyUser001'
go
This procedure is being deprecated I think, but researching it will show some "missing link" informaiton.
Use MyDatabase001
GO
declare #returnValue int
EXEC #returnValue = sp_change_users_login 'Update_One', 'MyUser001', 'MyUser001'
print '/#returnValue/'
print #returnValue
print ''
Below is a script I wrote to add users to logins and as dbusers and map to some roles.
It uses SQLCMD Mode. But it is a "over the years" effort as I tried to write code to create users , and it wouldn't throw errors if the user was already added.
/*
--SqlCmd Notes:
--Remove comments and space between ":" and "setvar" to run in sqlcmd mode.
--!!! Checked in code MUST *recomment out* the setvars below !!! (Putting a space between the ":" and the "setvar" is sufficient)
-- (This is not preferred behavior, the issue has been reported at http://connect.microsoft.com/SQLServer/feedback/details/382007/in-sqlcmd-scripts-setvar-should-have-a-lower-precedence-than-command-line-variable-assignments )
: setvar ErrorOutputFileFromCommandLine "c:\wuwutemp\sqlcommmanderrorfile.txt"
: setvar DBNAME "MyDatabaseName"
: setvar DBUSERNAME "MyDomain\someDomainUserThatExists"
*/
Use [$(DBNAME)]
GO
:Error $(ErrorOutputFileFromCommandLine)
declare #databaseName varchar(64)
select #databaseName = db_name()
print '/#databaseName/'
print #databaseName
print ''
set nocount on
declare #CONST_DB_DATAREADER_ROLE varchar(64)
select #CONST_DB_DATAREADER_ROLE = 'db_datareader'
declare #CONST_DB_BACKUPOPERATOR_ROLE varchar(64)
select #CONST_DB_BACKUPOPERATOR_ROLE = 'db_backupoperator'
declare #UserNameHolder table ( IdentityID int identity(101,1) , DatabaseName varchar(128) , LoginName varchar(256) , MassagedLoginName varchar(264) , RoleName varchar(64) not null , AlreadyProcessed bit default 0 not null )
INSERT INTO #UserNameHolder ( DatabaseName , LoginName , RoleName ) values ( '$(DBNAME)' , '$(DBUSERNAME)' , #CONST_DB_DATAREADER_ROLE )
--INSERT INTO #UserNameHolder ( DatabaseName , LoginName , RoleName ) values ( '$(DBNAME)' , '$(DBUSERNAME)' , #CONST_DB_BACKUPOPERATOR_ROLE )
/* Below this line is "common logic code" */
Update #UserNameHolder Set MassagedLoginName = LoginName
/*
sp_grantlogin does NOT like brackets around a domain/user
example : EXEC sp_grantlogin #loginame = N'[MyDomain\MyUser]'
The "massaging" below is a work around to this issue
*/
Update #UserNameHolder Set MassagedLoginName = RIGHT(MassagedLoginName , LEN(MassagedLoginName) -1 ) where LEN(MassagedLoginName)>0 AND LEFT( MassagedLoginName,1)='['
Update #UserNameHolder Set MassagedLoginName = LEFT( MassagedLoginName , LEN(MassagedLoginName) -1 ) where LEN(MassagedLoginName)>0 AND RIGHT(MassagedLoginName,1)=']'
/* Use a iffy rule to figure out NT Names */
--Update #UserNameHolder Set IsNTName = 1 where LEN(LoginName)>0 AND LEFT( LoginName,1)='[' AND RIGHT(LoginName,1)=']'
-- public is built in, do not process it
Update #UserNameHolder Set AlreadyProcessed = 1 where UPPER(LoginName) = UPPER('public')
select * from #UserNameHolder
declare #CurrentIdentityID int
declare #CurrentLoginName varchar(256)
declare #CurrentMassagedLoginName varchar(256)
declare #CurrentDatabaseName varchar(64)
--declare #CurrentIsNTName bit
declare #CurrentRoleName varchar(64)
declare #sp_grantdbaccess_return_value_total int
select #sp_grantdbaccess_return_value_total = 0
declare #sp_addrolemember_return_value_total int
select #sp_addrolemember_return_value_total = 0
while exists (select null from #UserNameHolder where AlreadyProcessed = 0)
begin
select #CurrentIdentityID = (select top 1 IdentityID from #UserNameHolder where AlreadyProcessed = 0)
print '#CurrentIdentityID'
print #CurrentIdentityID
print ''
select #CurrentLoginName = ( select top 1 LoginName from #UserNameHolder where IdentityID = #CurrentIdentityID )
select #CurrentMassagedLoginName = ( select top 1 MassagedLoginName from #UserNameHolder where IdentityID = #CurrentIdentityID )
select #CurrentDatabaseName = ( select top 1 DatabaseName from #UserNameHolder where IdentityID = #CurrentIdentityID )
--select #CurrentIsNTName = ( select top 1 IsNTName from #UserNameHolder where IdentityID = #CurrentIdentityID )
select #CurrentRoleName = ( select top 1 RoleName from #UserNameHolder where IdentityID = #CurrentIdentityID )
print '#CurrentLoginName'
print #CurrentLoginName
print ''
print '#CurrentMassagedLoginName'
print #CurrentMassagedLoginName
print ''
print '#CurrentDatabaseName'
print #CurrentDatabaseName
print ''
--print '#CurrentIsNTName'
--print #CurrentIsNTName
--print ''
print '#CurrentRoleName'
print #CurrentRoleName
print ''
if(1=1) /* 1=1 is helpful while debugging, set to 1=2 to exclude */
begin
-- select name, loginname from master.dbo.syslogins where loginname = #currentLoginName and isntname = 1)
if not exists (select null from master.dbo.syslogins where UPPER(loginname) = UPPER(#CurrentLoginName) ) -- and isntname = 1)
begin
print 'About to execute sp_grantlogin for user:'
print #CurrentMassagedLoginName
EXEC sp_grantlogin #loginame = #CurrentMassagedLoginName
print ''
print ''
print 'About to execute sp_defaultdb for user:'
print #CurrentMassagedLoginName
EXEC sp_defaultdb #loginame = #CurrentMassagedLoginName , #defdb = #CurrentDatabaseName
print ''
print ''
end
else
begin
print 'NOT EXECUTED : sp_grantlogin'
print 'NOT EXECUTED : sp_defaultdb'
end
end
----------------------------------------
declare #sp_grantdbaccess_return_value int
declare #sp_change_users_login_return_value int
declare #needToRunThisIteration bit
select #needToRunThisIteration = 0
-- declare #currentLoginName varchar(64)
if(1=1) /* 1=1 is helpful while debugging, set to 1=2 to exclude */
begin
if not exists
(
select * from master.dbo.syslogins ml inner join dbo.sysusers
su on ml.sid = su.sid where
su.uid < 6382
and
UPPER(ml.name) = UPPER(#CurrentMassagedLoginName)
)
begin
if not exists
(
/* NOTE, this database name variable must be updated if copying/pasting 'common logic code' between database deployments (NEED_TO_REPLACE_A_VALUE) */
select * from master.dbo.syslogins ml Where
UPPER(ml.name) = UPPER(#CurrentMassagedLoginName)
and UPPER(ml.dbname) = UPPER('$(DBNAME)')
)
begin
select #needToRunThisIteration = 1
end
end
if not exists
(
/* NOTE, this database name variable must be updated if copying/pasting 'common logic code' between database deployments (NEED_TO_REPLACE_A_VALUE) */
select * FROM [$(DBNAME)]..sysusers su Where
UPPER(su.name) = UPPER(#CurrentMassagedLoginName)
)
begin
select #needToRunThisIteration = 1
end
/*
Debug
select dbname , loginname , * from master.dbo.syslogins ml where dbname != 'master' order by 1 , 2
select * FROM TPA2Report..sysusers su
*/
declare #stringNameMatchesButNotSid bit
select #stringNameMatchesButNotSid = 0
IF EXISTS (
SELECT dbUsers.name as NameToFix , *
FROM sys.sysusers dbUsers
join sys.syslogins sqlServerLogins on UPPER(dbUsers.name) = UPPER(sqlServerLogins.name)
WHERE dbUsers.sid != sqlServerLogins.sid
and UPPER(dbUsers.name) = UPPER(#CurrentMassagedLoginName)
)
begin
select #stringNameMatchesButNotSid = 1
end
if (#needToRunThisIteration!=0)
begin
if #stringNameMatchesButNotSid = 0
begin
print 'About to execute sp_grantdbaccess for user:'
print #CurrentMassagedLoginName
exec #sp_grantdbaccess_return_value = sp_grantdbaccess #CurrentMassagedLoginName
print ''
print '#sp_grantdbaccess_return_value'
print #sp_grantdbaccess_return_value
print ''
select #sp_grantdbaccess_return_value_total = #sp_grantdbaccess_return_value_total + #sp_grantdbaccess_return_value
end
else
begin
/* There is a mismatched "sid" issue, but with the same names. This will address the issue. */
print 'About to execute sp_change_users_login for user:'
print #CurrentMassagedLoginName
EXEC #sp_change_users_login_return_value = sp_change_users_login #Action='update_one', #UserNamePattern=#CurrentMassagedLoginName,#LoginName=#CurrentMassagedLoginName;
print ''
print '#sp_change_users_login_return_value'
print #sp_change_users_login_return_value
print ''
end
end
end
-------------------------------------------------------
declare #sp_addrolemember_return_value int
if(1=1) /* 1=1 is helpful while debugging, set to 1=2 to exclude */
begin
if not exists
(
SELECT null --, role_principal_id, member_principal_id, princ1.name AS
role_name, princ2.name As member_name
FROM sys.database_role_members AS S LEFT JOIN sys.database_principals AS
princ1 ON S.role_principal_id = princ1.principal_id AND princ1.type = 'R'
LEFT JOIN sys.database_principals AS princ2 ON S.member_principal_id =
princ2.principal_id AND princ2.type IN ('S', 'U')
WHERE princ1.name = #CurrentRoleName and UPPER(princ2.name) = UPPER(#CurrentMassagedLoginName)
)
begin
print 'About to execute sp_grantdbaccess for user:'
print #CurrentMassagedLoginName
print 'For the role:'
print #CurrentRoleName
exec #sp_addrolemember_return_value = sp_addrolemember #CurrentRoleName, #CurrentMassagedLoginName
print ''
print '#sp_addrolemember_return_value'
print #sp_addrolemember_return_value
print ''
select #sp_addrolemember_return_value_total = #sp_addrolemember_return_value_total + #sp_addrolemember_return_value
end
end
Update #UserNameHolder Set AlreadyProcessed = 1 Where IdentityID = #CurrentIdentityID
end
print '/#sp_grantdbaccess_return_value_total/'
print #sp_grantdbaccess_return_value_total
print '/#sp_addrolemember_return_value_total/'
print #sp_addrolemember_return_value_total
GO

T - SQL statement IF EXIST SELECT and INSERT

How can I make this possible..really need advice? I want to get the id where my condition is met, then used it in my queries.
IF EXISTS (Select sn_id as snid FROM device.sn WHERE dname_id = 62 and sn_value = '123415')
BEGIN
SELECT MAX(id) AS maxid FROM device.list
INSERT INTO parts (sn_id,device_id) VALUES (snid, maxid)
END
ELSE
BEGIN
PRINT 'id does not exist'
return
END
You can use variables to store the results from the two queries and then use those values in your INSERT statement.
If you're using Microsoft SQL Server then the following may work (but there may be superficial syntax errors as it hasn't been tested). Note that I've assumed the type of your columns is int.
DECLARE #snid int
SET #snid = NULL
Select #snid = sn_id FROM device.sn WHERE dname_id = 62 and sn_value = '123415'
IF #snid IS NULL
BEGIN
PRINT 'id does not exist'
END
ELSE
BEGIN
DECLARE #maxid int
SELECT #maxid = MAX(id) AS maxid FROM device.list
INSERT INTO parts (sn_id,device_id) VALUES (#snid, #maxid)
END
In SQLServer. This script at first insert records and after checks count of the inserted rows
INSERT INTO parts (sn_id, device_id)
SELECT sn_id, (SELECT MAX(id) FROM device.list)
FROM device.sn
WHERE dname_id = 62 and sn_value = '123415'
IF ##ROWCOUNT = 0 PRINT 'id does not exist'
Declare #snid int=null
Declare #maxid int=1 -- if no value exists in device.list table
set #snid = (select sn_id from device.sn WHERE dname_id = 62 and sn_value = '123415')
set #maxid = (select MAX(id) AS maxid FROM device.list)
if #snid is not null
Begin
insert into parts(sn_id,device_id)
values(#snid,#maxid)
End
else
Begin
print 'ID does not exist'
End

Resources