procedure to insert columns from one table to another - sql

i want to insert columns date, service and service_count from an existing table to a new table. i want to do it using a procedure but it's not working.
set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
go
ALTER PROC [dbo].[SP_INSERTCOLOUMNS]
AS
BEGIN
DECLARE #SQLS NVARCHAR(MAX)
SET #SQLS = 'insert into test(date,service,service_count)
select date,service,count(service) from tbl_OBD_CDRS
group by date,service'
PRINT #SQLS
EXEC SP_EXECUTESQL #SQLS
PRINT 'INSERTED SUCCESSFULLY'
END
if i run the insert command independently it works fine. if i run it using this procedure it says Command(s) completed successfully, but no changes are made in the table "test".

I don't see any issue in your script. Why don't you try to check count in Test table. See if no of records increases in your Test table.
set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
go
ALTER PROC [dbo].[SP_INSERTCOLOUMNS]
AS
BEGIN
select date,service,count(service) from tbl_OBD_CDRS
group by date,service
DECLARE #SQLS NVARCHAR(MAX)
SET #SQLS = 'insert into test(date,service,service_count)
select date,service,count(service) from tbl_OBD_CDRS
group by date,service'
PRINT #SQLS
EXEC SP_EXECUTESQL #SQLS
PRINT 'INSERTED SUCCESSFULLY'
END
Try to run this on SQL Server and post your result.
EXEC [dbo].[SP_INSERTCOLOUMNS]

ALTER PROC [dbo].[SP_INSERTCOLOUMNS]
AS
BEGIN
-- select date,service,count(service) from tbl_OBD_CDRS
-- group by date,service
insert into test(date,service,service_count)
select date,service,count(service) from tbl_OBD_CDRS Group by date,service
PRINT 'INSERTED SUCCESSFULLY'
END
use this if any error in table / datatype it throw directly

Related

Dynamic SQL throws error complaining scalar variable is not defined

I am copying my bulk data to SQL Server (table name: TmpTable) via C# code and then I want to update the table with following stored procedure:
ALTER PROCEDURE dbo.sp_Update_Locations
(#lupdatedNoRow VARCHAR(10) OUT)
AS
SET NOCOUNT ON
BEGIN
DECLARE #mttblfaximages3_sql NVARCHAR(500) ='UPDATE testAdmin.dbo.mttblFaxImages2 set fRemoteStorageLocation = temp.RemoteStorageLocation, fRemoteImageName = temp.RemoteImageName from testAdmin.dbo.mttblFaxImages2 T INNER JOIN #TmpTable Temp ON (T.fFaxId=Temp.PrimaryId AND T.fFaxPageId=Temp.SecondaryId); DROP TABLE #TmpTable;SELECT #lupdatedNoRow = cast(##rowcount as VARCHAR)'
EXEC sp_executesql #mttblfaximages3_sql
select #lupdatedNoRow
END
I see update works fine but c# throws exception after that
Must declare the scalar variable "#lupdatedNoRow"
I want to return the number of rows updated.
How I should modify my stored procedure to return number of rows updated?
you need to define & pass the variable #lupdatedNoRow into the sp_executesql
EXEC sp_executesql #mttblfaximages3_sql,
N'#lupdatedNoRow varchar(10) OUTPUT',
#lupdatedNoRow OUTPUT
select #lupdatedNoRow

Unable to pull out resetSet for insert within stored procedure

I have been looking online for a few days to find a solution and
I may be asking the wrong questions.
I have the following stored proc which on insertion of a row to a db I want to get back the output int (#outResult). This is the stored proc :
USE [DB1]
GO
/****** Object: StoredProcedure [dbo].[storedProc1] Script Date: 04/12/2016 10:16:23 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[storedProc1]
-- Add the parameters for the stored procedure here
#inParam nvarchar(max),
#outResult int = 0 OUTPUT
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
IF NOT EXISTS
(
SELECT ID
FROM dbo.table1
WHERE Field1 = #inParam
)
Insert into [DB1].[dbo].[table1]
(
Field1
)
Values (
#inParam
)
SET #outResult = SCOPE_IDENTITY()
END
When I run the following SQL and try to retrieve the resultSet :
SELECT * FROM (EXEC storedProc1 'field1')
I get the following error:
"Incorrect syntax near the keyword 'exec'"
Maybe I am approaching this problem wrong from the first place?
I will continue to look into this and provide a solution if I find one.Any ideas?
To get the value of the output parameter you need to supply the call to the SP with an output argument. You do that by specifying the OUTPUT option on the second parameter.
DECLARE #returned_ID INT;
EXEC storedProc1 #inParam = 'field1',
#outResult = #returned_ID OUTPUT
SELECT #returned_ID
If you want to retrieve just the out parameter, then You can read it as :
DECLARE #output int
EXEC storedProc1 'field1',#output OUTPUT
SELECT #output

SQL Server 2008: Insert variable into DML statements using Stored Procedure

I have the following procedure:
CREATE PROCEDURE [dbo].[Test1]
AS
BEGIN
INSERT INTO [My_Database].[My_Schema].[My_Table]
(...lists columns...)
SELECT ... lots of columns from joined query...
END
Instead of hardcoding "[My_Database].[My_Schema]", I now want to select it as a variable from a predefined table like this:
CREATE PROCEDURE [dbo].[Test1]
AS
BEGIN
SELECT #myDB = [My_DB] FROM [my_custom_table]
--INSERT INTO [My_Database].[My_Schema].[My_Table]
INSERT INTO #myDB.[My_Table]
(...lists columns...)
SELECT ... lots of columns from joined query...
END
It does not work if I use it like above. I need to use:
EXEC sp_executesql (entire_sql_statement_in_quotes)
My problem is that I have a lot of these procedures to change to using a variable instead of being hardcoded. It will take forever to convert each statement to a long string.
Is there some other way to do it? What am I missing?
Regards
One idea, you could drop and recreate a synonym using dynamic SQL at the beginning of each procedure, then you can leave each Insert statement as Insert Into MySynonym
DROP SYNONYM MySynonym -- Must create it first before running this bit!
DECLARE #sql nvarchar(max)
SET #SQL = 'CREATE SYNONYM MySynonym
FOR ' + #myDB + '.test1'
EXEC sp_Executesql #sql
INSERT INTO MySynonym
SELECT ...
This would give you a peice of code you could copy paste into each SP. If the table you are inserting into is different for each SP, you could declare that too and build it into your CREATE SYNONYM statement
SET #SQL = 'CREATE SYNONYM MySynonym
FOR ' + #myDB + '.' + #MyTable
to Truncate each table first you would need to use DynamicSQL also, as you cannot delete on a synonym
SET #SQL = 'Truncate Table ' + #MyTable
EXEC sp_Executesql #sql

"WHEN OTHERS THEN NULL" in SQL Server 2005

tracking_table is a log table declared as follows:
create table tracking_table (my_command nvarchar(500), my_date datetime);
Please suppose you have the following block of SQL SERVER 2005 code, declared within a SQL Server 2005 job:
DECLARE #my_statement NVARCHAR(500)
delete from tracking_table
SET #my_statement = 'ALTER INDEX ALL ON my_user.dbo.my_fact_table REBUILD WITH (FILLFACTOR = 90)'
insert into tracking_table values (#my_statement,getdate())
EXEC (#my_statement)
SET #my_statement = 'ALTER INDEX ALL ON my_user.dbo.my_second_table REBUILD WITH (FILLFACTOR = 90)'
insert into tracking_table (#my_statement,getdate())
EXEC (#my_statement)
At runtime, if the first statement (ALTER INDEX ALL ON my_user.dbo.my_fact_table REBUILD WITH (FILLFACTOR=90)) fails, the second statement which acts on my_second table WON'T be executed.
I would like to know how could I modify the SQL Server 2005 code, in order to skip any error, going forward (in Oracle I would say, WHEN OTHERS THEN NULL).
How could I achieve this?
Thank you in advance for your kind help.
I cannot advice to suppress errors, but if you really want to do it, I think you can try:
declare #my_statement nvarchar(500)
begin try
delete from tracking_table
end try
begin catch
print null // or errormessage
end catch
begin try
set #my_statement = 'ALTER INDEX ALL ON my_user.dbo.my_fact_table REBUILD WITH (FILLFACTOR = 90)'
insert into tracking_table values (#my_statement,getdate())
exec (#my_statement)
end try
begin catch
print null // or errormessage
end catch
begin try
set #my_statement = 'ALTER INDEX ALL ON my_user.dbo.my_second_table REBUILD WITH (FILLFACTOR = 90)'
insert into tracking_table (#my_statement,getdate())
exec (#my_statement)
end try
begin catch
print null // or errormessage
end catch
you can also create procedure
create procedure sp_executesql_Suppress_Errors
(
#stmt nvarchar(max)
)
as
begin
begin try
exec sp_executesql
#stmt = #stmt
end try
begin catch
print null // or errormessage
end catch
end
and then call it with your statements. I also advice you to use exec sp_executesql instead of exec (see Dynamic SQL - EXEC(#SQL) versus EXEC SP_EXECUTESQL(#SQL))

SQL select print out results of stored procedure

My businesses application supports only reporting with selected data from SQL server.In one business process I have very complicated stored procedure which using others stored procs and it was designed to print out results as log of job done. What I want to catch that print out and select it as varchar(max) so my app can handle that data and display to user.
Here is sample scenario described in TSQL code:
create procedure sp_test_print_out
as
begin
Print 'Test';
print 'Test 1';
end
go
create procedure sp_test_print_out_to_select
as
declare #printOut varchar(max)
set #printOut = exec sp_test_print_out --How I can achieve this ?
select #printOut
end
go
exec sp_test_print_out_to_select
You can try setting the values in output parameter
create procedure sp_test_print_out
#printMessages varchar(max) output
as
begin
set #printMessages='Test'
Print 'Test';
set #printMessages= #printMessages + CHAR(10)
set #printMessages= #printMessages + 'Test 1'
print 'Test 1';
end
go
create procedure sp_test_print_out_to_select
as
begin
declare #printOut varchar(max)
exec sp_test_print_out #printOut output -- can be achieved using output parameter ?
select #printOut
end
go
exec sp_test_print_out_to_select
There is also one rough and probably BAD way to get selected data from print commands inside stored procedure.
Command xp_cmdshell and sqlcmd can do the JOB. Xp_cmdshell is mostly disabled and not allowed to use at most of SQL servers because of security reasons.
Here is code:
CREATE TABLE #temp
(OUTPUT VARCHAR(MAX));
declare #cmd varchar(800);
set #cmd = 'sqlcmd -d RobotTest -Q "exec sp_test_print_out"';
INSERT INTO #TEMP
exec xp_cmdshell #cmd ;
select output from #temp;
drop table #temp;