OldSlowDog
Programmer
This is the first time I do dynamic query. I have a hard time to figure this out. Please help.
I am trying to walk through 10 different db in a SQL server with one query to pull the sales data into a collective table in Corpdb.
We have 10 stores and each store is a db in the server with the same table names and etc.:
SQLSVR_XZY(SQL SERVER 9.0..)
Corpdb
Store1db
Store2db
Store3db
Store4db
... and so on
My plan is to query a location table which contains the dbnames and using cursor and one dynamic sql to pull the sales data into a collective table. I got the rest going except the dynamic sql. Here is the dynamic sql:
CREATE PROCEDURE SalesReport_sp
(
@Storeid int,
@BegDt datetime,
@EndDt datetime,
@dbNme varchar(20)
)
AS
DECLARE @SQLCmd
SET @SQLCmd = 'SELECT '+ @Storeid + ' ItemId, DailySaleAmt, QuantityCnt FROM ' + quotename(@dbName) + '.dbo.DailySales_tbl WHERE TranDate > ' + @BegDt ' AND TranDate <= ' + @EndDt + ' ORDER BY TranDate'
INSERT INTO Corpdb.dbo.DlySales_tbl
EXEC sp_EXECUTESQL @SQLCmd, N'@Storeid int', @Storeid
I couldn't get the BegDt and EndDt working.
Thanks for helping.
I am trying to walk through 10 different db in a SQL server with one query to pull the sales data into a collective table in Corpdb.
We have 10 stores and each store is a db in the server with the same table names and etc.:
SQLSVR_XZY(SQL SERVER 9.0..)
Corpdb
Store1db
Store2db
Store3db
Store4db
... and so on
My plan is to query a location table which contains the dbnames and using cursor and one dynamic sql to pull the sales data into a collective table. I got the rest going except the dynamic sql. Here is the dynamic sql:
CREATE PROCEDURE SalesReport_sp
(
@Storeid int,
@BegDt datetime,
@EndDt datetime,
@dbNme varchar(20)
)
AS
DECLARE @SQLCmd
SET @SQLCmd = 'SELECT '+ @Storeid + ' ItemId, DailySaleAmt, QuantityCnt FROM ' + quotename(@dbName) + '.dbo.DailySales_tbl WHERE TranDate > ' + @BegDt ' AND TranDate <= ' + @EndDt + ' ORDER BY TranDate'
INSERT INTO Corpdb.dbo.DlySales_tbl
EXEC sp_EXECUTESQL @SQLCmd, N'@Storeid int', @Storeid
I couldn't get the BegDt and EndDt working.
Thanks for helping.