Create parameter - sql-server

(How) Can I Sql Server create a parameter that is automatically populated from data - in other words equivalent to SAS' "Proc Sql; into:" - functionality
In SAS I can store the number of rows in a table, mytable, into a macro variable, n_rows. I am looking for something like this in sql server.
proc sql noprint;
select count(*) into :n_rows
from mytable
quit;
%put &n_rows.;

Maybe I am missing something, but is this what you're looking for?
declare #numberOfRows int = (select count(*) from myTable)
select #numberOfRows

Related

Log for affected rows of select and insert command - SQL Server- Help needed

so I have some commands which I want to put in a stored procedure(then stored procedure executed by a job) to automate. What I need is to make some sort of log(file or table?!) where to have the affected rows a select or insert did and also how long they took to execute. So can you help me with some ideas? thanks
Examples below:
truncate table table_xyz
insert into table_aaa
select * from (select * from table_dsd union all select * from table_dsdf)
ex: "40234 rows affected" ; 00:00:35
some selects
one simple way would be to do like this
declare #startdate datetime=getdate()
select * from sometbl
--log data
select ##rowcount,datediff(minute,#startdate,getdate())

Incorrect syntax near 'Root' SQL returning XML

How to correct the following query in order to return an xml.
I am getting the following error "Line 14: Incorrect syntax near 'Root'.
" How to fix this?
declare #v_CurrentDate datetime
set #v_CurrentDate = '2016-07-28'
if exists (select 1
from mydb.dbo.Orders
where OrderDate = #v_CurrentDate)
begin
SELECT 'mydb' AS Client, PrimaryKey, Ship_Status, OrderDate, ApprovedDate, AcknowledgeDate, ShipToSiteName, AntShipDate
FROM mydb.dbo.Orders
WHERE (Ship_Status = 'Acknowledged')
ORDER BY PrimaryKey DESC
for xml auto, type, elements, Root('Orders')
end
else
select cast('<NoRecords>No order records available for this date.</NoRecords>' as xml)
You're going to have to supply an example of the failing query.
Screenshot the SQL Server Management Studio when you run:
create database TestFoo;
go
use TestFoo
go
create table users (userid int); select userid from users for xml auto, type, elements, root('foo');
go
use master
go
drop database TestFoo

Executing stored procedure in select query

I'm using SQL Server 2008 R2 and I am trying to run a query where a stored procedure will also be executed.
The query is:
select a.custnmbr, a.custname, a.salsterr, b.itemnmbr, b.itemdesc, d.slprsnid ,exec dbo.QtySoldPerMonth a.custnmbr, b.itemnmbr, #year
from rm00101_temp a, iv00101_temp b
inner join sop30300_RPT c on b.itemnmbr = c.itemnmbr
inner join sop30200_RPT d on c.sopnumbe = d.sopnumbe
where
b.itemnmbr like #houseCode + '%' and itmclscd like #classCode + '%'
AND DATEPART(year, d.docdate) = #year
group by a.custnmbr, a.custname, a.salsterr, b.itemnmbr, b.itemdesc, d.slprsnid
order by d.slprsnid, b.itemnmbr
What I'm really asking is how do I go about including the execution of the dbo.QtySoldPerMonth stored procedure in the select query? Also, the parameters for the stored procedures are: #custNo = a.custnmbr, #itemNo = b.itemnmbr and #year = #year.
Any help on how to rewrite the query to execute the sp will be appreciated.
create temp table for sp output
exec stored proc into temp table
join temp table to the rest of your query
create table #temp(yourCol1 int, your Col2 int...);
insert #temp(yourCol1,yourCol1...)
exec dbo.QtySoldPerMonth
select * from blah
join #temp t on (blah.blah=t.id...)
You can't execute a stored procedure as part of another query.
See if you can use a view of UDF to represent the same structure that the SP would return.
Edit
Another option: execute the stored procedure first and use the results in your main query.
You can't incorporate SP results to query, but you can dump SP to a table. Example:
http://blog.sqlauthority.com/2009/09/23/sql-server-insert-values-of-stored-procedure-in-table-use-table-valued-function/
But in your case it's not an option, as you want SP result with different parameters for every row; unless you modify SP so it returns a result set that you can later use after inserting it into table.

How to convert a SQL Server result set to XML after the fact?

Is there a way to cause the result set of a SQL Server stored procedure (or any result set, after the fact) to be encoded in XML format?
I want the result set to be encoded in XML as if the FOR XML RAW clause was used during selection.
However the complex stored procedure logic and its internal SELECT statements should not be modified to return XML because the procedure is used for its standard/non-XML result set most of the time.
Update: Emphasis on the fact I'm looking for an answer in the SQL Server environment - the
results should be returned as if SQL Server has directly encoded them itself, as XML, just like it does when using the built-in XML features like the FOR XML clause.
You would insert the data from the SP into a temp table, then select from that FOR XML
This won't work if the SP itself already does a INSERT .. EXEC SPROC because you cannot nest them
Working examples
use tempdb;
create proc giveme
as
select a = 1, b = GETDATE()
union all
select 2, b = '20100101'
Using INSERT.. EXEC
declare #t table (a int, b datetime)
insert #t
exec giveme
select * from #t for xml raw
Using OPENQUERY
exec sp_addlinkedserver 'localhost'
exec sp_serveroption #server = 'localhost'
,#optname = 'DATA ACCESS'
,#optvalue = 'TRUE'
select *
from openquery(localhost, 'exec tempdb..giveme')
for xml raw
You could try using OPENROWSET in cooperation with FOR XML to do the transformation.
By 'after the fact', do you mean still within the SQL Server environment? Or are you talking about a client program?
Within SQL, you could probably write a sproc that acts as a wrapper for your other sprocs, along these lines. The wrapper sproc would handle the FOR XML work.
In .NET, there are a number of ways to do this.
You can try inserting the result set from the stored procedure into a table variable( or temporary table) and selecting the table rows with the FOR XML clause.
Here is an example:
DECLARE #MyDataTable AS TABLE ( col1 int,...., colN int)
Make sure that the #MyDataTable has the same columns as the stored procedure result set(s).
INSERT INTO #MyDataTable
EXECUTE mysp_GetData #param1=value,....,#paramN;
SELECT * FROM #MyDataTable
FOR XML AUTO

How to Log Number of Rows affected by SSIS Execute SQL Task

When I execute a sql statement like "Select ...", I can only see "...100%" completed...
I want to log the number of rows affected.
How can we do that?
run your SELECT from within a stored procedure, where you can log the rowcount into a table, or do anything else to record it...
CREATE PROCEDURE SSIS_TaskA
AS
DECLARE #Rows int
SELECT ... --your select goes here
SELECT #Rows=##ROWCOUNT
INSERT INTO YourLogTable
(RunDate,Message)
VALUES
(GETDATE(),'Selected '+CONVERT(varchar(10),ISNULL(#Rows,0))+' rows in SSIS_TaskA')
GO
When you use a SQL Task for a select most of the time you give as destination a DataSet Object, you can count the number of ligne from the DataSet
I believe you could leverage a t-sql output clause on your update or insert statement and capture that as an ssis variable....or just drop it into a sql table.
here is an example...its crappy, but it is an example
UPDATE TOP (10) HumanResources.Employee
SET VacationHours = VacationHours * 1.25
OUTPUT INSERTED.EmployeeID,
DELETED.VacationHours,
INSERTED.VacationHours,
INSERTED.ModifiedDate
INTO #MyTableVar;
You could output ##ROWCOUNT anyplace you need it to be.
Here is output syntax
http://technet.microsoft.com/en-us/library/ms177564.aspx

Resources