![]() | |
![]() |
| | Thread Tools | Display Modes |
#1
| |||
| |||
|
#2
| |||
| |||
|
#3
| |||
| |||
|
|
The syntax to use INSERT INTO is like this: INSERT INTO TABLE2 (<column_list>) SELECT <column_list FROM TABLE1 WHERE COL1 = 'A' A few brief notes: - the <column_list> will list your columns (like COL1, COL2, COL3, etc.) - the <column_list> must contain the same number of columns in both clauses (INSERT INTO and SELECT) - if you do not specify the <column_list> in the INSERT INTO clause (as you did in your sample query), then the <column_list> in SELECT must much all columns in TABLE2 - the columns have to be of the same data type and size, being able to implicitly convert, or explicitly converted via CAST/CONVERT - in your case if the "confirm_hash" column does not exists in the destination table, then you have to drop it from the column list (or alter TABLE2 before the insert to add the column) - you do not have to list the IDENTITY column as it will get automatically the value based on the IDENTITY (of if you want to force a value in that column, run before the query SET IDENTITY_INSERT TABLE2 ON) If you post your CREATE TABLE statements for both tables, some sample data and desired results you can get much better help. HTH, Plamen Ratchevhttp://www.SQLStudio.com |
#4
| |||
| |||
|
#5
| |||
| |||
|
|
The syntax error is because of the commas in the WHERE clause. The conditions in the WHERE clause are logical expressions and you have to use AND or OR between expressions based on what you need to filter. A trimmed down example is: INSERT INTO Table1 (column1, column2) SELECT column1, column2 FROM Table2 WHERE column1 = @column1 AND column2 = @column2 All that said, I am a bit puzzled why you decided to write this stored procedure and the purpose of passing those column parameters. If you just need to copy the Table2 to Table1, then directly run the statement like this: INSERT INTO Table1 (column1, column2, -- ... the rest of the columns go here column17) SELECT column1, column2, -- ... the rest of the columns go here column17 FROM Table2 And then if you have any filters that you need to apply to the columns from Table2, you can add the WHERE clause. Also, you could wrap that statement in a stored procedure, but I just do not see the purpose of passing all those column parameters to the SP. Can you explain why you added them and how you plan to execute the SP, and maybe an example of what parameters you pass? If you are trying to perform something like dynamic searching (that is filter on multiple variable conditions), then you may want to read Erland Sommarskog's article on dynamic search conditions:http://www.sommarskog.se/dyn-search.html HTH, Plamen Ratchevhttp://www.SQLStudio.com |
#6
| |||
| |||
|
#7
| |||
| |||
|
Ok, now it is more clear what you are trying to do... ![]() Yes, stored procedure is best here, as it can reuse previously cached execution plan. Perhaps something like this: CREATE PROCEDURE ConfirmUserRegistration @confirmation_cd NVARCHAR(50) AS SET NOCOUNT ON; BEGIN TRY BEGIN TRAN INSERT INTO Users (egdate, pass, role, squestion, sanswer, zcode, altemail, email, bdaymonth, bdayday, bdayyear, gender, sitename, city, state, country, lastName, firstName) SELECT regdate, pass, role, squestion, sanswer, zcode, altemail, email, bdaymonth, bdayday, bdayyear, gender, sitename, city, state, country, lastName, firstName FROM TempRegistration WHERE confirm = @confirmation_cd; COMMIT TRAN; END TRY BEGIN CATCH IF (XACT_STATE()) = -1 BEGIN ROLLBACK TRAN; END ELSE IF (XACT_STATE()) = 1 BEGIN COMMIT TRAN; END DECLARE @ErrorMessage NVARCHAR(4000), @ErrorSeverity INT, @ErrorState INT, @ErrorNumber INT, @ErrorLine INT, @ErrorProcedure NVARCHAR(200), @ErrMessage NVARCHAR(4000); SELECT @ErrorMessage = ERROR_MESSAGE(), @ErrorSeverity = ERROR_SEVERITY(), @ErrorState = ERROR_STATE(), @ErrorNumber = ERROR_NUMBER(), @ErrorLine = ERROR_LINE(), @ErrorProcedure = COALESCE(ERROR_PROCEDURE(), '-'); SET @ErrMessage = N'Error %d, Level %d, State %d, Procedure %s, Line %d, ' + N'Message: '+ ERROR_MESSAGE(); RAISERROR( @ErrMessage, @ErrorSeverity, 1, @ErrorNumber, @ErrorSeverity, @ErrorState, @ErrorProcedure, @ErrorLine ); END CATCH; GO Then in your code call the SP like this (I just typed here, please check for syntax, I've been using more C# lately and could be missing something): Using connection As New SqlConnection(ConfigurationManager.ConnectionStrin gs("myConnStr").ConnectionString) Try Dim command As SqlCommand = New SqlCommand( _ "ConfirmUserRegistration", connection) command.CommandType = CommandType.StoredProcedure Dim parameter As SqlParameter = command.Parameters.Add( _ "@confirmation_cd ", SqlDbType.NVarChar, _ 50) parameter.Value = "8c37a0737eegd64532rgdf56g5ec3f75aab5d9e7a7120 77" command.Connection.Open() command.ExecuteNonQuery() Catch exSQL As SqlException ' Log and show error Catch exGen As Exception ' Log and show error End Try End Using HTH, Plamen Ratchevhttp://www.SQLStudio.com |
#8
| |||
| |||
|
|
On Jun 4, 8:15 pm, "Plamen Ratchev" <Pla... (AT) SQLStudio (DOT) com> wrote: Ok, now it is more clear what you are trying to do... ![]() Yes, stored procedure is best here, as it can reuse previously cached execution plan. Perhaps something like this: CREATE PROCEDURE ConfirmUserRegistration @confirmation_cd NVARCHAR(50) AS SET NOCOUNT ON; BEGIN TRY BEGIN TRAN INSERT INTO Users (egdate, pass, role, squestion, sanswer, zcode, altemail, email, bdaymonth, bdayday, bdayyear, gender, sitename, city, state, country, lastName, firstName) SELECT regdate, pass, role, squestion, sanswer, zcode, altemail, email, bdaymonth, bdayday, bdayyear, gender, sitename, city, state, country, lastName, firstName FROM TempRegistration WHERE confirm = @confirmation_cd; COMMIT TRAN; END TRY BEGIN CATCH IF (XACT_STATE()) = -1 BEGIN ROLLBACK TRAN; END ELSE IF (XACT_STATE()) = 1 BEGIN COMMIT TRAN; END DECLARE @ErrorMessage NVARCHAR(4000), @ErrorSeverity INT, @ErrorState INT, @ErrorNumber INT, @ErrorLine INT, @ErrorProcedure NVARCHAR(200), @ErrMessage NVARCHAR(4000); SELECT @ErrorMessage = ERROR_MESSAGE(), @ErrorSeverity = ERROR_SEVERITY(), @ErrorState = ERROR_STATE(), @ErrorNumber = ERROR_NUMBER(), @ErrorLine = ERROR_LINE(), @ErrorProcedure = COALESCE(ERROR_PROCEDURE(), '-'); SET @ErrMessage = N'Error %d, Level %d, State %d, Procedure %s, Line %d, ' + N'Message: '+ ERROR_MESSAGE(); RAISERROR( @ErrMessage, @ErrorSeverity, 1, @ErrorNumber, @ErrorSeverity, @ErrorState, @ErrorProcedure, @ErrorLine ); END CATCH; GO Then in your code call the SP like this (I just typed here, please check for syntax, I've been using more C# lately and could be missing something): Using connection As New SqlConnection(ConfigurationManager.ConnectionStrin gs("myConnStr").ConnectionString) Try Dim command As SqlCommand = New SqlCommand( _ "ConfirmUserRegistration", connection) command.CommandType = CommandType.StoredProcedure Dim parameter As SqlParameter = command.Parameters.Add( _ "@confirmation_cd ", SqlDbType.NVarChar, _ 50) parameter.Value = "8c37a0737eegd64532rgdf56g5ec3f75aab5d9e7a7120 77" command.Connection.Open() command.ExecuteNonQuery() Catch exSQL As SqlException ' Log and show error Catch exGen As Exception ' Log and show error End Try End Using HTH, Plamen Ratchevhttp://www.SQLStudio.com Thanks again Plamen. This thread has been very helpful. I have a final question. How do I handle cases where the confirmation code doesn't exist? Say a user is trying to guess a code - How would the stored procedure catch a mismatch and return the result to VB.NET so the appropriate message can be sent to the user? Thanks again for all your help. Peter |
.
#9
| |||
| |||
|
#10
| |||
| |||
|
|
I will try to sketch here the answer to both questions: 1). To detect that the confirmation code exists, you can check the number of rows affected by the insert (using @@rowcount), and then return that value to the client using an output parameter. If the number of rows is 1 (I assume you have either a primary key or UNIQUE constraint on the confirmation code column so duplicates are not possible), then you know you had a code match, if 0 then there was no match. Here is an abbreviated code of the SP: CREATE PROCEDURE ConfirmUserRegistration @confirmation_cd NVARCHAR(50), @numrows INT OUTPUT AS -- .... BEGIN TRAN INSERT INTO Users (egdate, pass, -- ... firstName) SELECT regdate, pass, -- ... firstName FROM TempRegistration WHERE confirm = @confirmation_cd; SET @numrows = @@rowcount; DELETE FROM TempRegistration WHERE confirm = @confirmation_cd; COMMIT TRAN; Note that you can directly perform the DELETE without checking the result of the INSERT, because if there is no match then there will be no rows deleted. If you want you can have an IF @numrows > 0 before executing the DELETE statement to run it only when there is a match. 2). On your client side, you have to define the output parameter and then check the results, abbreviated code here: '... connection, command and first parameter initialization go here ' now add the output parameter parameter = command.Parameters.Add( _ "@numrows", SqlDbType.Int) parameter.Direction = ParameterDirection.Output '... open the connection and execute command go here ' retrieve the output value If (command.Parameters("@numrows").Value = 1) Then ' we have a match and confirmation is complete Else ' confirmation code is invalid - show alert End If HTH, Plamen Ratchevhttp://www.SQLStudio.com |
![]() |
| Thread Tools | |
| Display Modes | |
| |