Use Excel VBA parameter to set Sql query declare variable - sql-server

Is there any solution to use VBA give parameter to my sql query,
My sql query need datetime to query period of salesdata,
And can have any control tool in excel?
SQL
declare #BegYMD nvarchar(10)
declare #EndYMD nvarchar(10)
declare #EmpEcr nvarchar(1)
declare #SysBraNoS nvarchar(2)
set #BegYMD=CONVERT(varchar(100),dateadd(year, -1, getdate()), 111)
set #EndYMD=CONVERT(varchar(100), GETDATE(), 111)
POWERBI query
declare #BegYMD nvarchar(10)
declare #EndYMD nvarchar(10)
declare #EmpEcr nvarchar(1)
declare #SysBraNoS nvarchar(2)
set #BegYMD='"& Date.ToText(StartDate) & "'
set #EndYMD='"& Date.ToText(EndDate) & "'
set #EmpEcr=''

Related

why I got error from report server by passing date/time object to datetime variable in stored procedure?

In my project, I am using reporting service to create report form SQL DB.
However, the error below is shown (ALL variable which of type datetime bring this error).
The value provided for the report parameter 'THE_DATE' is not
valid for its type.
I will tell you all the information I can provided to you for this question.
In report project,
I build up a field which its f(x) is =IIf
(Parameters!THE_DATE.Value Is
Nothing,Nothing,Format(Parameters!THE_DATE.Value,"yyyy-MM-dd"))
I also create a variable named THE_DATE which of type Date/Time and set Allow null value.
In the dataset, the query is
EXEC MC_GetDateReport #THE_DATE, #DEPARTMENT,
#TYPE, #ID
In the SQL:
the stored procedure is shown as below:
ALTER procedure [dbo].[MC_GetDateReport ]
#THE_DATE as datetime = null,
#DEPARTMENT as nvarchar(MAX) = null,
#TYPE as nvarchar(MAX) = null,
#LAN_ID as nvarchar(MAX) = null
AS
SET NOCOUNT ON
DECLARE
#SQLSTRING nvarchar(MAX),
#PARAMETER nvarchar(500);
SET #CASE = 0;
SELECT #SQLSTRING = N'';
Could anyone tell me why it say The 'THE_DATE' is not valid as both variable is type of datetime?

Populate ReportViewer with a dynamic stored procedure

I need to fill a report with a stored procedure like this one:
CREATE PROCEDURE [dbo].SelectDataToReport
#table_name varchar (25),
#period varchar (25)
AS
BEGIN
DECLARE #mySql nvarchar (MAX)
SET NOCOUNT ON;
SET #mySql = 'SELECT * FROM '+#table_name+' WHERE Period = '+#period+''
EXEC (#mySql)
END
But the report only accepts stored procedure like this one:
CREATE PROCEDURE [dbo].SelectCSAT
#Period varchar (25)
AS
BEGIN
SELECT ID, CSAT, Period
FROM CSAT
WHERE Period = #Period
END
So, I don't know if there's another way to fill the report. The thing is that the database tables and columns will be changed and when the report is generated, the user selects which table and period he wants.
I appreciate your help!
all you have to do is do (if your column counts never vary, you cannot have dynamic columns)
(i do this all the time)
print #mySQL
1) Then take that statement and put it at the top of your stored procedure.
2) comment all your dynamic code out
3) go into ssrs and creating a data set will work.
4) go back into your stored procedure and comment out your sql statement and restore your dynamic code (dont forget to put back exec(#mySql)
for code example do this
CREATE PROCEDURE [dbo].SelectDataToReport
#table_name varchar (25),
#period varchar (25)
AS
BEGIN
SELECT ID , CSAT , Period FROM CSAT WHERE Period = '.'
/*DECLARE #mySql nvarchar (MAX)
SET NOCOUNT ON;
SET #mySql = 'SELECT ID , CSAT , Period FROM '+#table_name+' WHERE Period = '+#period+''
EXEC (#mySql)*/
END

How to SELECT * into a SQL table incremntally by date?

I have a SQL Server table called "tblProducts".
Sometimes I backup this table by making a copy of it with this simple query:
SELECT *
INTO [test01].[dbo].[tblProducts_20141206]
FROM [test01].[dbo].[tblProducts]
Every time when making a backup, the date is included in the table name.
I would like to create a SQL Job that runs this kind of query once every week.
Is it possible to maybe in a stored procedure or declaring a variable to achieve this that allows the backed-up table name to be named like [tblProducts_todaysDate]?
Thanks.
If you are using a SP, you can do something like:
CREATE PROC sp_createATable
#name VARCHAR(20) AS
CREATE TABLE #name
...
do your insert
Or, if you want to, w/o SP:
DECLARE #name varchar(20)
SET #name = 'tblName' + SELECT CONVERT(VARCHAR(8), GETDATE(), 112) AS [YYYYMMDD]
CREATE TABLE #name
...
do your insert
You need Dynamic SQL to create the tables names appended with date.
CREATE PROC usp_createtable( #tablename VARCHAR(20),
#Dbname VARCHAR(20),
#SchemaName VARCHAR(20))
AS
BEGIN
DECLARE #sql NVARCHAR(max)
SET #sql =' SELECT * INTO '+#Dbname+'.'+#SchemaName+'.'+#tablename+'CONVERT(VARCHAR(8), GETDATE(), 112) FROM '+#Dbname+'.'+#SchemaName+'.'+#tablename''
EXEC sp_executesql
#sql
END

OpenXML in SQL Server with dd/MM/yyyy format gives conversion error

I have a SQL Server stored procedure with a XML string as a parameter. The XML string has date tag with dd/MM/yyyy date format. While using the OpenXML it gives conversion error. Even if I have the sql user login has default language setup as British English. It works fine with MM-dd-yyyy date format.
This is my code
Declare #XML Nvarchar(MAX)
Set #XML= '<root><ContractNo>100213</ContractNo><ContractDate>25/6/2012</ContractDate></root>'
Declare #idoc int
-- Create an internal representaion of XML
EXEC sp_xml_preparedocument #idoc OUTPUT, #XML
-- Get the data from XML into respective variables
SELECT ContractNo
,ContractDate
FROM OPENXML(#idoc,'root',2)
WITH ( ContractNo nvarchar(30)
,ContractDate Datetime
)
Error:
Msg 241, Level 16, State 1, Line 10
Conversion failed when converting date and/or time from character string.
For reference, since you are using SQL Server 2005+, you should start using the XML datatype and XQuery.
Declare #XML nvarchar(max);
Set #XML = '<root><ContractNo>100213</ContractNo>
<ContractDate>25/6/2012</ContractDate></root>';
DECLARE #realXML xml;
set #realXML = #XML;
SELECT #realXML.value('(/root/ContractNo)[1]', 'varchar(max)') ContractNo,
CONVERT(DATETIME,
#realXML.value('(/root/ContractDate)[1]', 'varchar(max)'),
103) ContractDate;
CONVERT() gives you flexibility in handling the dates, but if you had to, you can set the dateformat setting. The British English language has a "dmy" setting that should work with your data. Check that something else isn't resetting the dateformat. Otherwise, set it explicitly before the batch. e.g. this works:
set dateformat dmy;
Declare #XML nvarchar(max);
Set #XML = '<root><ContractNo>100213</ContractNo>
<ContractDate>25/6/2012</ContractDate></root>';
DECLARE #realXML xml;
set #realXML = #XML;
SELECT #realXML.value('(/root/ContractNo)[1]', 'varchar(max)') ContractNo,
#realXML.value('(/root/ContractDate)[1]', 'datetime') ContractDate;
You can get your date as varchar and use convert in the field list using style 103 dd/mm/yyyy.
SELECT ContractNo
,CONVERT(datetime, ContractDate, 103) as ContractDate
FROM OPENXML(#idoc,'root',2)
WITH ( ContractNo nvarchar(30)
,ContractDate varchar(10)
)
Declare #XML Nvarchar(MAX)
Set #XML= '<root><ContractNo>100213</ContractNo><ContractDate>25/6/2012</ContractDate></root>'
Declare #idoc int
-- Create an internal representaion of XML
EXEC sp_xml_preparedocument #idoc OUTPUT, #XML
-- Get the data from XML into respective variables
SELECT ContractNo
,Convert(Datetime, ContractDate,103)
FROM OPENXML(#idoc,'root',2)
WITH ( ContractNo nvarchar(30)
,ContractDate nvarchar(10)
)

SQL Server Logging/User Tracking Capabilities

We have recently converted an Access Application to store the date on SQL server. The forms still reside in the MS Access, but are linked through file DSN's to SQL server.
A question came up of the capabilities to track user activity within SQL server.
I have speculated that if we set up individual users in SQL server and use these individual accounts when setting up the DSN's on the user's computers that perhaps then we could use SQL server to track user activity. Is this true?
We currently have SQL server 2005 standard but will be upgrading to 2008 relatively soon.
Thanks for any suggestions!
When you upgrade to SQL 2008 you have Change Data Capture.
I work currently on tracking DDL changes , so here is one DDL trigger with the needed 2 functions and table structure ... Before running the code set ext props for your database for "DbVersion"(e.g. 2.3.4) and "DbType" (e.g. dev , test , prod ) and replace the [ga] namespace with the one with your choice or create one ...
Edit: fixed bug with null Version if object is new ...
USE [GA_DEV]
GO
/****** Object: DdlTrigger [TraceDbChanges] Script Date: 05/07/2009 11:15:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create trigger [TraceDbChanges]
on database
for create_procedure, alter_procedure, drop_procedure,
create_table, alter_table, drop_table,
create_function, alter_function, drop_function ,
create_trigger , alter_trigger , drop_trigger
as
set nocount on
declare #data xml
set #data = EVENTDATA()
declare #DbVersion varchar(20)
set #DbVersion =(select ga.GetDbVersion())
declare #DbType varchar(20)
set #DbType =(select ga.GetDbType())
declare #DbName varchar(256)
set #DbName =#data.value('(/EVENT_INSTANCE/DatabaseName)[1]', 'varchar(256)')
declare #EventType varchar(256)
set #EventType =#data.value('(/EVENT_INSTANCE/EventType)[1]', 'varchar(50)')
declare #ObjectName varchar(256)
set #ObjectName = #data.value('(/EVENT_INSTANCE/ObjectName)[1]', 'varchar(256)')
declare #ObjectType varchar(25)
set #ObjectType = #data.value('(/EVENT_INSTANCE/ObjectType)[1]', 'varchar(25)')
declare #TSQLCommand varchar(max)
set #TSQLCommand = #data.value('(/EVENT_INSTANCE/TSQLCommand)[1]', 'varchar(max)')
declare #opentag varchar(4)
set #opentag= '<'
declare #closetag varchar(4)
set #closetag= '>'
declare #newDataTxt varchar(max)
set #newDataTxt= cast(#data as varchar(max))
set #newDataTxt = REPLACE ( REPLACE(#newDataTxt , #opentag , '<') , #closetag , '>')
-- print #newDataTxt
declare #newDataXml xml
set #newDataXml = CONVERT ( xml , #newDataTxt)
declare #Version varchar(50)
set #Version = #newDataXml.value('(/EVENT_INSTANCE/TSQLCommand/CommandText/Version)[1]', 'varchar(50)')
-- if we are dropping take the version from the existing object
if ( SUBSTRING(#EventType , 0 , 5)) = 'DROP'
set #Version =( select top 1 [Version] from ga.DbObjChangeLog where ObjectName=#ObjectName order by [LogId] desc)
if ( #Version is null)
set #Version = '1.0.0'
declare #Description varchar(max)
set #Description = #newDataXml.value('(/EVENT_INSTANCE/TSQLCommand/CommandText/Description)[1]', 'varchar(max)')
declare #ChangeDescription varchar(max)
set #ChangeDescription = #newDataXml.value('(/EVENT_INSTANCE/TSQLCommand/CommandText/ChangeDescription)[1]', 'varchar(max)')
declare #LoginName varchar(256)
set #LoginName = #data.value('(/EVENT_INSTANCE/LoginName)[1]', 'varchar(256)')
declare #FirstName varchar(50)
set #FirstName= (select [FirstName] from [ga].[LoginsForUsers] where [LoginName] = #LoginName)
declare #LastName varchar(50)
set #LastName = (select [LastName] from [ga].[LoginsForUsers] where [LoginName] = #LoginName)
declare #SchemaName sysname
set #SchemaName = #data.value('(/EVENT_INSTANCE/SchemaName)[1]', 'sysname');
--declare #Description xml
--set #Description = #data.query('(/EVENT_INSTANCE/TSQLCommand/text())')
print 'VERSION IS ' + #Version
print #newDataTxt
print cast(#data as varchar(max))
-- select column_name from information_schema.columns where table_name ='DbObjChangeLog'
insert into [ga].[DbObjChangeLog]
(
[DatabaseName] ,
[SchemaName],
[DbVersion] ,
[DbType],
[EventType],
[ObjectName],
[ObjectType] ,
[Version],
[Description],
[ChangeDescription],
[SqlCommand] ,
[LoginName] ,
[FirstName],
[LastName]
)
values(
#DbName,
#SchemaName,
#DbVersion,
#DbType,
#EventType,
#ObjectName,
#ObjectType ,
#Version,
#Description,
#ChangeDescription,
#newDataTxt,
#LoginName ,
#FirstName ,
#LastName
)
GO
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
DISABLE TRIGGER [TraceDbChanges] ON DATABASE
GO
ENABLE TRIGGER [TraceDbChanges] ON DATABASE
GO
Is this true?
Yes, triggers on tables to capture changes would work. You could also set up a server side trace to log login events to a table if you were after that kind of info. Be more specific for some more answers.

Resources