SQL Procedure Meaning - sql-server

Can someone to explain me what the next procedure does?
CREATE PROCEDURE [add_100*Clients-runView2-del_50*Reductions] AS
DECLARE #procName NVARCHAR(100) = OBJECT_NAME(##PROCID), #currentName NVARCHAR(50)
DECLARE #index int
INSERT INTO TestRuns (Description, StartAt, EndAt)
VALUES ('Add Clients - View 2 - Delete Reductions', GETDATE(), null)
DECLARE #currentID int
SET #currentID = (SELECT SCOPE_IDENTITY())
SET #index = CHARINDEX('-', #procName)
WHILE #index > 0
BEGIN
SET #currentName = SUBSTRING(#procName, 1, #index-1)
SET #procName = SUBSTRING(#procName, #index+1, (LEN(#procName) - #index))
SET #index = CHARINDEX('-', #procName)
EXEC #currentName
END
SET #currentName = #procName
EXEC #currentName
UPDATE TestRuns
SET EndAt = GETDATE()
WHERE TestRunID = #currentID
GO
I can't understand what does getDate and how it influences the tables.

The purpose of the procedure lies within
EXEC #currentName.
I believe this is some sort of performance test where you see how much time procedures takes to run
I guess you are passing some sort of procedure names separated by - and parse each procedure and run them.
While running them , you are recording your start of the time using GetDate and after everything is run, end of the run using GetDate.(As GetDate gives you the current time, the difference will tell you how long did it take to run all the procedures.
You record that information in an audit table called TestRuns.

Related

How to get and use the value returned by a stored procedure to a INSERT INTO... SELECT... statement

I am just new in SQL language and still studying it. I'm having hard time looking for answer on how can I use the stored procedure and insert value into a table.
I have this stored procedure:
CREATE PROCEDURE TestID
AS
SET NOCOUNT ON;
BEGIN
DECLARE #NewID VARCHAR(30),
#GenID INT,
#BrgyCode VARCHAR(5) = '23548'
SET #GenID = (SELECT TOP (1) NextID
FROM dbo.RandomIDs
WHERE IsUsed = 0
ORDER BY RowNumber)
SET #NewID = #BrgyCode + '-' + CAST(#GenID AS VARCHAR (30))
UPDATE dbo.RandomIDs
SET dbo.RandomIDs.IsUsed = 1
WHERE dbo.RandomIDs.NextID = #GenID
SELECT #NewID
END;
and what I'm trying to do is this:
INSERT INTO dbo.Residents([ResidentID], NewResidentID, [ResLogdate],
...
SELECT
[ResidentID],
EXEC TestID ,
[ResLogdate],
....
FROM
source.dbo.Resident;
There is a table dbo.RandomIDs containing random 6 digit non repeating numbers where I'm pulling out the value via the stored procedure and updating the IsUsed column of the table to 1. I'm transferring data from one database to another database and doing some processing on the data while transferring. Part of the processing is generating a new ID with the required format.
But I can't get it to work Sad I've been searching the net for hours now but I'm not getting the information that I need and that the reason for my writing. I hope someone could help me with this.
Thanks,
Darren
your question is little bit confusing, because you have not explained what you want to do. As i got your question, you want to fetch random id from randomids table and after performed some processing on nextid you want to insert it into resident table [newresidentid] and end of the procedure you fetch data from resident table. if i get anything wrong feel free to ask me.
your procedure solution is following.
CREATE PROCEDURE [TestId]
AS
SET NOCOUNT ON;
BEGIN
DECLARE #NEWID NVARCHAR(30)
DECLARE #GENID BIGINT
DECLARE #BRGYCODE VARCHAR(5) = '23548'
DECLARE #COUNT INTEGER
DECLARE #ERR NVARCHAR(20) = 'NO IDS IN RANDOM ID'
SET #COUNT = (SELECT COUNT(NEXTID) FROM RandomIds WHERE [IsUsed] = 0)
SET #GENID = (SELECT TOP(1) [NEXTID] FROM RandomIds WHERE [IsUsed] = 0 ORDER BY [ID] ASC)
--SELECT #GENID AS ID
IF #COUNT = 0
BEGIN
SELECT #ERR AS ERROR
END
ELSE
BEGIN
SET #NEWID = #BRGYCODE + '-' + CAST(#GENID AS varchar(30))
UPDATE RandomIds SET [IsUsed] = 1 WHERE [NextId] = #GENID
INSERT INTO Residents ([NewResidentId] , [ResLogDate] ) VALUES (#NEWID , GETDATE())
SELECT * FROM Residents
END
END
this procedure will fetch data from your randomids table and perform some processing on nextid than after it directs insert it into resident table and if you want to insert some data through user you can use parameter after declaring procedure name
E.G
CREATE PROCEDURE [TESTID]
#PARAM1 DATATYPE,
#PARAM2 DATATYPE
AS
BEGIN
END
I'm not convinced that your requirement is a good one but here is a way to do it.
Bear in mind that concurrent sessions will not be able to read your update until it is committed so you have to kind of "lock" the update so you will get a block until you're going to commit or rollback. This is rubbish for concurrency, but that's a side effect of this requirement.
declare #cap table ( capturedValue int);
declare #GENID int;
update top (1) RandomIds set IsUsed=1
output inserted.NextID into #cap
where IsUsed=0;
set #GENID =(select max( capturedValue) from #cap )
A better way would be to use an IDENTITY or SEQUENCE to solve your problem. This would leave gaps but help concurrency.

SQL Server stored procedure: wait for a delete's trigger to finish before continuing in the procedure

My stored procedure executes a delete statement that sets off a trigger that can't record who deleted the row, but records a blank for changed_by.
Then the stored procedure updates the changed_by with the username it was given.
Half the time, part 2 of the below stored procedure finds the results of the trigger, the other half of the time, it doesn't find the results of the trigger, so there is nothing to update.
How can I "yield" control and ensure the update's trigger finishes before continuing with the stored procedure?
(In comments you see some things I've tried so far that haven't worked)
DROP PROCEDURE IF EXISTS dbo.deleteAndUpdateChangedByInAuditTrail
GO
CREATE PROCEDURE dbo.deleteAndUpdateChangedByInAuditTrail
(#tableName VARCHAR(100),
#pkIDColName VARCHAR(100),
#pkIDValue NUMERIC,
#delUser VARCHAR(100) )
AS
BEGIN TRANSACTION;
-- PART 1: DO THE DELETE:
DECLARE #JUST_BEFORE_DELETION_TIMESTAMP AS DATETIME2;
SET #JUST_BEFORE_DELETION_TIMESTAMP = CONVERT(varchar, SYSDATETIME(), 121);
DECLARE #DELETION_TEMPLATE AS VARCHAR(MAX);
SET #DELETION_TEMPLATE = 'delete from {THE_TABLE_NAME} WHERE {PK_ID_COL_NAME} = {PK_ID_VALUE}';
SET #DELETION_TEMPLATE = REPLACE(#DELETION_TEMPLATE, '{THE_TABLE_NAME}', #tableName);
SET #DELETION_TEMPLATE = REPLACE(#DELETION_TEMPLATE, '{PK_ID_COL_NAME}', #pkIDColName);
SET #DELETION_TEMPLATE = REPLACE(#DELETION_TEMPLATE, '{PK_ID_VALUE}', #pkIDValue);
--PRINT #DELETION_TEMPLATE
EXEC (#DELETION_TEMPLATE);
COMMIT TRANSACTION;
BEGIN TRANSACTION;
-- PART 2: UPDATE THE AUDIT_TRAIL:
DECLARE #TOTAL_NUM_ROWS_UPDATED_WITH_USERNAME AS NUMERIC;
SET #TOTAL_NUM_ROWS_UPDATED_WITH_USERNAME = 0;
--DECLARE #TOTAL_TRIES_SO_FAR AS NUMERIC;
--SET #TOTAL_TRIES_SO_FAR = 0;
--WHILE #TOTAL_NUM_ROWS_UPDATED_WITH_USERNAME < 1 AND #TOTAL_TRIES_SO_FAR < 5
--BEGIN
--SET #TOTAL_TRIES_SO_FAR = #TOTAL_TRIES_SO_FAR + 1;
--WAITFOR DELAY '00:00:01.000' -- SEEN IT FAIL FOR 4 SECONDS :(
DECLARE #UPDATE_AUDIT_TRAIL_TEMPLATE AS VARCHAR(MAX);
SET #UPDATE_AUDIT_TRAIL_TEMPLATE = 'update AUDIT_TRAIL set changed_by = ''{CHANGED_BY}'' WHERE upper(table_name) = upper(''{THE_TABLE_NAME}'') and table_pk_value = {PK_ID_VALUE} and CONVERT(varchar, changed_at, 121) >= ''{CHANGED_AT}'' ';
SET #UPDATE_AUDIT_TRAIL_TEMPLATE = REPLACE(#UPDATE_AUDIT_TRAIL_TEMPLATE, '{CHANGED_BY}', #delUser);
SET #UPDATE_AUDIT_TRAIL_TEMPLATE = REPLACE(#UPDATE_AUDIT_TRAIL_TEMPLATE, '{THE_TABLE_NAME}', #tableName);
SET #UPDATE_AUDIT_TRAIL_TEMPLATE = REPLACE(#UPDATE_AUDIT_TRAIL_TEMPLATE, '{PK_ID_VALUE}', #pkIDValue);
SET #UPDATE_AUDIT_TRAIL_TEMPLATE = REPLACE(#UPDATE_AUDIT_TRAIL_TEMPLATE, '{CHANGED_AT}', #JUST_BEFORE_DELETION_TIMESTAMP);
--PRINT #UPDATE_AUDIT_TRAIL_TEMPLATE
EXEC (#UPDATE_AUDIT_TRAIL_TEMPLATE);
SELECT #TOTAL_NUM_ROWS_UPDATED_WITH_USERNAME = ##ROWCOUNT;
--END
COMMIT TRANSACTION;
RETURN #TOTAL_NUM_ROWS_UPDATED_WITH_USERNAME;
GO
Triggers don't get executed asynchronously. The next step after the DELETE will not happen until the trigger is finished.
If you are seeing something that makes you think otherwise, there is some other reason for it. It's not because the trigger "didn't finish".

SQL Server if statement does not execute as expected

I am trying to use the following stored procedure but there are some instances WHERE only the incremental happens AND the code does not run. What I need is that, when the program enters the IF statement, either it should run both the statements or None.
Stored procedure goes like this:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[spflpunch]
AS
BEGIN
DECLARE #id NUMERIC(18,0)
DECLARE #studname NVARCHAR(50)
DECLARE #punchtime DATETIME
DECLARE #samedaycount NUMERIC(2)
SELECT #id = (MAX(lastid)) FROM [smartswype].[dbo].[read]
PRINT #id
SELECT #studname = studname
FROM [SSWYPE_WEBDB].[dbo].[attdview]
WHERE id =#id
PRINT #studname
SELECT #punchtime = punchtime
FROM [SSWYPE_WEBDB].[dbo].[attdview]
WHERE id = #id
PRINT #punchtime
--SELECT #punchvarchar = CONVERT(VARCHAR(10),#punchtime, 103) + ' ' + CONVERT(VARCHAR(5), #punchtime, 14)
IF #id = (SELECT MAX(id) FROM [SSWYPE_WEBDB].[dbo].[attdview])
BEGIN
SELECT #samedaycount = COUNT(*)
FROM [SSWYPE_WEBDB].[dbo].[attdview]
WHERE (studname = #studname
AND CONVERT(DATE, punchtime) = CONVERT(DATE, #punchtime)) -- If firstpunch = 1 then it is the first punch
PRINT #samedaycount
IF #samedaycount =1
BEGIN
INSERT INTO [smartswype].[dbo].[firstlastpunch] ([studname], [DATE], [punch1], [punch2])
VALUES(#studname, CONVERT(DATE, #punchtime), #punchtime, NULL);
UPDATE [smartswype].[dbo].[read]
SET lastid = #id + 1;
END
ELSE IF (#samedaycount > 1)
BEGIN
UPDATE [smartswype].[dbo].[firstlastpunch]
SET punch2 = #punchtime
WHERE (studname = #studname AND DATE = CONVERT(DATE, #punchtime));
UPDATE [smartswype].[dbo].[read]
SET lastid = #id + 1;
END
END
END
If you want to ensure that both or none of the statements run, you should wrap the contents of the if statement in a transaction.
By wrapping it in a transaction, you can ensure that if one statement fails, that the other statement will not run.
Here is a link to the docs on transactions in SQL Server
https://learn.microsoft.com/en-us/sql/t-sql/language-elements/commit-transaction-transact-sql

Must declare the scalar variable

I wrote this SQL in a stored procedure but not working,
declare #tableName varchar(max) = 'TblTest'
declare #col1Name varchar(max) = 'VALUE1'
declare #col2Name varchar(max) = 'VALUE2'
declare #value1 varchar(max)
declare #value2 varchar(200)
execute('Select TOP 1 #value1='+#col1Name+', #value2='+#col2Name+' From '+ #tableName +' Where ID = 61')
select #value1
execute('Select TOP 1 #value1=VALUE1, #value2=VALUE2 From TblTest Where ID = 61')
This SQL throws this error:
Must declare the scalar variable "#value1".
I am generating the SQL dynamically and I want to get value in a variable. What should I do?
The reason you are getting the DECLARE error from your dynamic statement is because dynamic statements are handled in separate batches, which boils down to a matter of scope. While there may be a more formal definition of the scopes available in SQL Server, I've found it sufficient to generally keep the following three in mind, ordered from highest availability to lowest availability:
Global:
Objects that are available server-wide, such as temporary tables created with a double hash/pound sign ( ##GLOBALTABLE, however you like to call # ). Be very wary of global objects, just as you would with any application, SQL Server or otherwise; these types of things are generally best avoided altogether. What I'm essentially saying is to keep this scope in mind specifically as a reminder to stay out of it.
IF ( OBJECT_ID( 'tempdb.dbo.##GlobalTable' ) IS NULL )
BEGIN
CREATE TABLE ##GlobalTable
(
Val BIT
);
INSERT INTO ##GlobalTable ( Val )
VALUES ( 1 );
END;
GO
-- This table may now be accessed by any connection in any database,
-- assuming the caller has sufficient privileges to do so, of course.
Session:
Objects which are reference locked to a specific spid. Off the top of my head, the only type of session object I can think of is a normal temporary table, defined like #Table. Being in session scope essentially means that after the batch ( terminated by GO ) completes, references to this object will continue to resolve successfully. These are technically accessible by other sessions, but it would be somewhat of a feat do to so programmatically as they get sort of randomized names in tempdb and accessing them is a bit of a pain in the ass anyway.
-- Start of session;
-- Start of batch;
IF ( OBJECT_ID( 'tempdb.dbo.#t_Test' ) IS NULL )
BEGIN
CREATE TABLE #t_Test
(
Val BIT
);
INSERT INTO #t_Test ( Val )
VALUES ( 1 );
END;
GO
-- End of batch;
-- Start of batch;
SELECT *
FROM #t_Test;
GO
-- End of batch;
Opening a new session ( a connection with a separate spid ), the second batch above would fail, as that session would be unable to resolve the #t_Test object name.
Batch:
Normal variables, such as your #value1 and #value2, are scoped only for the batch in which they are declared. Unlike #Temp tables, as soon as your query block hits a GO, those variables stop being available to the session. This is the scope level which is generating your error.
-- Start of session;
-- Start of batch;
DECLARE #test BIT = 1;
PRINT #test;
GO
-- End of batch;
-- Start of batch;
PRINT #Test; -- Msg 137, Level 15, State 2, Line 2
-- Must declare the scalar variable "#Test".
GO
-- End of batch;
Okay, so what?
What is happening here with your dynamic statement is that the EXECUTE() command effectively evaluates as a separate batch, without breaking the batch you executed it from. EXECUTE() is good and all, but since the introduction of sp_executesql(), I use the former only in the most simple of instances ( explicitly, when there is very little "dynamic" element of my statements at all, primarily to "trick" otherwise unaccommodating DDL CREATE statements to run in the middle of other batches ). #AaronBertrand's answer above is similar and will be similar in performance to the following, leveraging the function of the optimizer when evaluating dynamic statements, but I thought it might be worthwhile to expand on the #param, well, parameter.
IF NOT EXISTS ( SELECT 1
FROM sys.objects
WHERE name = 'TblTest'
AND type = 'U' )
BEGIN
--DROP TABLE dbo.TblTest;
CREATE TABLE dbo.TblTest
(
ID INTEGER,
VALUE1 VARCHAR( 1 ),
VALUE2 VARCHAR( 1 )
);
INSERT INTO dbo.TblTest ( ID, VALUE1, VALUE2 )
VALUES ( 61, 'A', 'B' );
END;
SET NOCOUNT ON;
DECLARE #SQL NVARCHAR( MAX ),
#PRM NVARCHAR( MAX ),
#value1 VARCHAR( MAX ),
#value2 VARCHAR( 200 ),
#Table VARCHAR( 32 ),
#ID INTEGER;
SET #Table = 'TblTest';
SET #ID = 61;
SET #PRM = '
#_ID INTEGER,
#_value1 VARCHAR( MAX ) OUT,
#_value2 VARCHAR( 200 ) OUT';
SET #SQL = '
SELECT #_value1 = VALUE1,
#_value2 = VALUE2
FROM dbo.[' + REPLACE( #Table, '''', '' ) + ']
WHERE ID = #_ID;';
EXECUTE dbo.sp_executesql #statement = #SQL, #param = #PRM,
#_ID = #ID, #_value1 = #value1 OUT, #_value2 = #value2 OUT;
PRINT #value1 + ' ' + #value2;
SET NOCOUNT OFF;
Declare #v1 varchar(max), #v2 varchar(200);
Declare #sql nvarchar(max);
Set #sql = N'SELECT #v1 = value1, #v2 = value2
FROM dbo.TblTest -- always use schema
WHERE ID = 61;';
EXEC sp_executesql #sql,
N'#v1 varchar(max) output, #v2 varchar(200) output',
#v1 output, #v2 output;
You should also pass your input, like wherever 61 comes from, as proper parameters (but you won't be able to pass table and column names that way).
Here is a simple example :
Create or alter PROCEDURE getPersonCountByLastName (
#lastName varchar(20),
#count int OUTPUT
)
As
Begin
select #count = count(personSid) from Person where lastName like #lastName
End;
Execute below statements in one batch (by selecting all)
1. Declare #count int
2. Exec getPersonCountByLastName kumar, #count output
3. Select #count
When i tried to execute statements 1,2,3 individually, I had the same error.
But when executed them all at one time, it worked fine.
The reason is that SQL executes declare, exec statements in different sessions.
Open to further corrections.
This will occur in SQL Server as well if you don't run all of the statements at once. If you are highlighting a set of statements and executing the following:
DECLARE #LoopVar INT
SET #LoopVar = (SELECT COUNT(*) FROM SomeTable)
And then try to highlight another set of statements such as:
PRINT 'LoopVar is: ' + CONVERT(NVARCHAR(255), #LoopVar)
You will receive this error.
-- CREATE OR ALTER PROCEDURE
ALTER PROCEDURE out (
#age INT,
#salary INT OUTPUT)
AS
BEGIN
SELECT #salary = (SELECT SALARY FROM new_testing where AGE = #age ORDER BY AGE OFFSET 0 ROWS FETCH NEXT 1 ROWS ONLY);
END
-----------------DECLARE THE OUTPUT VARIABLE---------------------------------
DECLARE #test INT
---------------------THEN EXECUTE THE QUERY---------------------------------
EXECUTE out 25 , #salary = #test OUTPUT
print #test
-------------------same output obtain without procedure-------------------------------------------
SELECT * FROM new_testing where AGE = 25 ORDER BY AGE OFFSET 0 ROWS FETCH NEXT 1 ROWS ONLY

Is there a way to import a long list of new users to DNN

I have a new DNN site and a long list of users that must be added. How can I create these new users with a script.
I have seen modules for sale but if possible I would like to avoid buying a module.
For anyone still searching for an open source module to import users, there is this one http://usersimporter.codeplex.com/ that works well with the latest DNN version. It takes an Excel spreadsheet as input.
I have had good luck using this module to import users. DNNVillage Import Export User Pro It imports and exports users using an easily modified XML file. If you use excel to insert your user list into the xml file and then import it you should be good to go. The best part is that the module is free.
I'm working with DNN 4.4 and 4.9 and had the same problem. My solution to this was to develop a DNN module for this that could import from CSV or TAB separated text file. My advice would be to either buy or develop a module.
If you are intersted in writting your own I could provide you with code snippets what to do. Just let me know...
Snowcovered has a few built modules out there - (http://www.snowcovered.com/snowcovered2/Default.aspx?tabid=295&search=import+user) -
I have also written scripts to do this from one or anther of spreadsheets or some other database
A sql script to do this really just needs to add the right info
heres most a script i use to import from some access dbs - may not be great or elegant but it works!
SET NOCOUNT ON;
declare #SQLText nvarchar(max)
DECLARE #ErrMsg nvarchar(4000), #ErrSeverity int
BEGIN TRY
BEGIN TRANSACTION
-- Insert statements for procedure here
DECLARE #ApplicationName nvarchar(256)
SET #ApplicationName = 'DotNetNuke'
DECLARE #LastName nvarchar(max)
DECLARE #FirstName nvarchar(max)
DECLARE #EmployeeID nvarchar(max)
DECLARE #ContactEmail nvarchar(max)
DECLARE UserLoop CURSOR Fast_Forward
FOR SELECT [Employee] as EmployeeID, isnull([LastName],'') as employee_Lastname, isnull([FirstName],'') as emplyee_firstname, 'na#na.com' as contactemail
from openrowset('Microsoft.ACE.OLEDB.12.0', 'Excel 8.0;Database=C:\_projects\hc.xls;HDR=YES', 'SELECT * FROM [Sheet1$]')
--WHERE CustomerID in (SELECT OldID FROM dbo.RCIWebApps_LocationInfo WHERE OwnerID = #NewCustomerNumber)
Open UserLoop
FETCH NEXT FROM UserLoop INTO #EmployeeID, #LastName, #FirstName, #ContactEmail
WHILE ##FETCH_STATUS = 0
BEGIN
----
---Make unique usernames - adding one to the list until it doesnt match
DECLARE #NewUsername nvarchar(max)
SET #NewUserName = REPLACE(#Firstname + '_' + #LastName, ',','_')
DECLARE #UserNameTest int
SET #UsernameTest = 1
DECLARE #UserNameNumber int
SET #UserNameNumber = 1
DECLARE #UserNameTemp nvarchar(max)
SET #UserNameTemp = #NewUserName
WHILE #UserNameTest > 0
BEGIN
SELECT #UsernameTest = count(*) FROM rcidnn..Users WHERE Username = #UserNameTemp
IF #USernametest > 0
BEGIN
SET #UsernameTemp = #NewUserName + convert(nvarchar(max),#UserNameNumber)
SET #UserNameNumber = #UserNameNumber + 1
END
END
SET #NewUserName = #UserNameTemp
----
DECLARE #Password nvarchar(128)
--From the existing user
SET #Password = 'iIFBTBSKXithnIDFau1miTih903eL/z5qgbcyMOflIM='
DECLARE #PasswordSalt nvarchar(128)
--From the existing user
SET #PasswordSalt = '4DmxPzt6MYScaGuwNHeUDw=='
DECLARE #PasswordQuestion nvarchar(256)
SET #PasswordQuestion = ''
DECLARE #PasswordAnswer nvarchar(128)
SET #PasswordAnswer = ''
DECLARE #IsApproved bit
SET #IsApproved = 1
DECLARE #CurrentTimeUtc datetime
SET #CurrentTimeUtc = GETDATE()
DECLARE #CreateDate datetime
SET #CreateDate = #CurrentTimeUtc
DECLARE #UniqueEmail int
SET #UniqueEmail = 0
DECLARE #PasswordFormat int
SET #PasswordFormat = 2 --NOTE: Value from existing user!
DECLARE #PortalId int
SET #PortalId = 6 --The id of your portal
Declare #UserId uniqueidentifier
DECLARE #DNNUserId int
--Make the stored procedure call
EXEC rcidnn.dbo.aspnet_Membership_CreateUser #ApplicationName, #NewUsername, #Password,
#PasswordSalt, #contactemail, #passwordquestion, #PasswordAnswer,
#IsApproved, #CurrentTimeUtc, #CreateDate, #UniqueEmail,
#PasswordFormat, #UserId
--Insert the record into the DotNetNuke users table
print #NewUsername
INSERT INTO rcidnn..users (Username, FirstName, LastName, IsSuperUser, Email,
DisplayName, UpdatePassword)
VALUES(#NewUsername, #FirstName, #LastName, 0, #ContactEmail, #Firstname + ' ' + #LastName, 0)
--Get the new userid, from the DNN users table
SELECT #dnnuserid = userid
FROM rcidnn..Users
WHERE username = #NewUsername
--Now, insert the record into the user portals table
INSERT INTO rcidnn..UserPortals (userId, PortalId, CreatedDate)
VALUES(#dnnuserid, #PortalId, GETDATE())
--Now Give the user permissions to the RECISTERED Users group
INSERT INTO rcidnn..UserRoles (userId, roleId)
SELECT #dnnuserid,
roleId
FROM rcidnn..Roles
WHERE (RoleName = 'Registered Users' or RoleName = 'Subscribers' or RoleName = 'G - Location View')
and portalid = #PortalId
--ADD info into profile??
INSERT rcidnn.dbo.UserProfile
VALUES ( #DNNUserID, 167, #NewCustomerNumber, null, 2, getdate())
----
FETCH NEXT FROM UserLoop INTO #EmployeeID, #LastName, #FirstName, #ContactEmail
END
CLOSE Userloop
DEALLOCATE userloop
COMMIT
Print 'Transfered'
END TRY
BEGIN CATCH
-- Whoops, there was an error
IF ##TRANCOUNT > 0
ROLLBACK
-- Raise an error with the details of the exception
SELECT #ErrMsg = ERROR_MESSAGE(),
#ErrSeverity = ERROR_SEVERITY()
RAISERROR(#ErrMsg, #ErrSeverity, 1)
END CATCH
The best product I have used is 'Bulk User Manager'. Not free, but WELL worth the $30. It will save hours of work, and Time is Money!
Here is the link to the product on the DNN Store:
http://store.dnnsoftware.com/home/product-details/bulk-user-manager-v33

Resources