0
I have the need to clone a record into a table but picking up the fields the way they are, the reason is that someone can insert or remove some column, so I don’t know which columns I have in the table at that time.
I created a precedent to do this, I pass an ID, it runs and returns me the new ID. I hope to be able to express myself and that someone can help me, follows below an example of the process I created.
ALTER PROCEDURE [dbo].[spClonaPedido]
-- Add the parameters for the stored procedure here
@PedidoId int,
@NovoId int output
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
DECLARE @COLUNA VARCHAR(100), @COLUNAS VARCHAR(MAX), @CLOCAR VARCHAR(MAX);
--- Inicializar a variavel
SET @COLUNAS = ''
SET @NovoId = ''
SET @CLOCAR = ''
--sempre declare que o cursor é do tipo LOCAL FAST_FORWARD.
--Local diz que é o scopo da execuçao e FAST_FORWARD significa que ele so vai pra frente.
DECLARE CURCOLUNAS CURSOR LOCAL FAST_FORWARD FOR SELECT COLUMN_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_CATALOG = 'MeusPedidos'
AND TABLE_SCHEMA= 'dbo'
AND TABLE_NAME = 'pedidos'
ORDER BY ORDINAL_POSITION
OPEN CURCOLUNAS
FETCH NEXT FROM CURCOLUNAS INTO @COLUNA
WHILE @@FETCH_STATUS = 0
BEGIN
SET @COLUNAS = @COLUNAS + ', ' + @COLUNA
FETCH NEXT FROM CURCOLUNAS INTO @COLUNA --- O into nesta linha
END
SET @COLUNAS= Right(@COLUNAS, len(@COLUNAS)-2)
SET @CLOCAR = 'INSERT INTO Pedidos ('+@COLUNAS+') SELECT '+@COLUNAS+' FROM Pedidos WHERE PedidoId = '+@PedidoId
EXEC(@CLOCAR)
SET @NovoId = SCOPE_IDENTITY()
RETURN @NovoId
CLOSE CURCOLUNAS;
DEALLOCATE CURCOLUNAS;
END
Yes, and what is your difficulty? Your
procedure
no longer works?– Sorack
and if you use the syntax without informing the columns ? https://www.w3schools.com/sql/sql_insert_into_select.asp
– Rovann Linhalis
Oops, Procedure is not working, it is giving error at the time of Insert. But the link you recommended is possible. The need to do it this way as I built it is that the moment that this process runs some new columns may appear in the table, then I thought to select all columns and not use the * not to be barred in the validation. But I appreciate the link.
– Robson Cabral