I already searched for a solution, but the answers weren't specific enough to solve my problem.
So I have this Statement:
IF NOT EXISTS
(SELECT InternalRepositoryId FROM Tfs_GitInterface.dbo.tbl_GitRepository WHERE Name = @repositoryName)
BEGIN
...
END
or of course also possible:
IF NOT EXISTS
(SELECT InternalRepositoryId FROM dbo.tbl_GitRepository WHERE Name = @repositoryName)
BEGIN
...
END
Its working completely fine. I would like to mention that dbo is a Schema to another database. Now I want to make something like this:
DECLARE @schema [nvarchar](400);
SET @schema = 'dbo';
IF NOT EXISTS
(SELECT InternalRepositoryId FROM @schema.tbl_GitRepository WHERE Name = @repositoryName)
BEGIN
...
END
or
DECLARE @schemaTable [nvarchar](400);
SET @schemaTable = 'dbo.tbl_GitRepository';
IF NOT EXISTS
(SELECT InternalRepositoryId FROM @schemaTable WHERE Name = @repositoryName)
BEGIN
...
END
Now I tried already some dynamic sql but it wouldn't work without errors:
DECLARE @schemaTable [nvarchar](400);
SET @schemaTable = 'dbo.tbl_GitRepository';
DECLARE @sql [nvarchar](4000);
SET @sql = 'SELECT InternalRepositoryId FROM ' + @schemaTable + ' WHERE Name = ' + @repositoryName;
IF NOT EXISTS
(EXECUTE sp_executesql @sql)
BEGIN
...
END
Then I get the error at EXECUTE: "Incorrect Syntax near 'EXECUTE'. Expecting '(', or SELECT" and some minor Errors.
Does anyone got an idea how to do this?
EDIT: The IF statement was the big problem